Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
from timeit import timeit
def t1():
# складываем 10 строк через + из переменной
t = 'text'
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t2():
# склеиваем список строк через метод join
arr = ['text'] * 10
for _ in range(1000):
s = ''.join(arr)
def t3():
# складываем через + но не из переменной а непосредственно инлайн объекты
for _ in range(1000):
s = 'text' + 'text' + 'text' + ... # всего 10 раз
Теперь каждую строку склейки запустим по 10М раз
>>> timeit(t1, number=10000)
0.21951690399964718
>>> timeit(t2, number=10000)
1.4978306379998685
>>> timeit(t3, number=10000)
0.2213820789993406
Хм, а нам говорили что через "+" это плохо и медленно ))) 😁
Тут стоит учитывать, что речь идёт о склейке множества длинных строк.
Давайте изменим условия:
def t4():
t = 'text'*100
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t5():
arr = ['text'*100] * 10
for _ in range(1000):
s = ''.join(arr)
def t6():
for _ in range(1000):
s = 'text'*100 + 'text'*100 + ... # всего 10 раз
>>> timeit(t4, number=10000)
12.795130728000004
>>> timeit(t5, number=10000)
2.642637542999182
>>> timeit(t6, number=10000)
0.2184546610005782
Вот, уже другой разговор, сразу видна разница, в среднем в 6 раз. Но погодите, почему последний тест t6() по скорости такой же как и t3()? Ведь строки теперь в 100 раз длиннее!
Это вопросы оптимизации кода, какие простые изменения ускоряют или замедляют выполнение программы. Мы столкнулись с примером обхода обращения к переменной. Например, именно так работает директива #define в С++, во время компиляции подставляя значение переменной вместо ссылки на неё.
В Python это тоже работает, но часто ли вы сможете встретить такой способ работы со строками? К сожалению, способ почти только теоретический.
В целом, тесты показали то, что мы хотели. Делаем выводы самостоятельно.
Полный листинг 🌍
#tricks
Title : " Triumphing Adventure "
Adventure awaits the brave,
Who can risk the life to crave.
Pursuits revealing mysteries,
Eager to challenge for victories.
The desire for discovery,
With enough effort and bravery.
Who possess essential qualities,
Like optimism, capabilities and sensibilities.
Life itself is an adventurous journey,
The challenging soul inside is burning.
The ones who master this adventure,
Can set up a record for others to venture.
#review#Cookie#optimism
🆕TokenPocket now supports the #Optimism MultiSig Wallet! optimismFND
> Both Mobile Wallet and Browser Extension Wallet!
MultiSig is one of the best ways to protect your #Crypto, with multiple protection, you can transfer, store, and trade your #Crypto in a more #SAFU situation.
👉 Visit https://tokenpocket.pro or https://extension.tokenpocket.pro/#/
👉 Tutorial https://help.tokenpocket.pro/en/wallet-faq-en/Multisig-Wallet/create
🚀 Select #Optimism and start your MultiSig journey with TokenPocket!
【Details】https://twitter.com/TokenPocket_TP/status/1709820851787530422
【Powered By】Crypto Box
🚨🚨 KyberSwap was exploited for around $48.3M on several networks #Arbitrum, #Optimism, #Ethereum and #Polygon and #Base.
- The top 4 affected assets include:
16,217 $ETH (all forms) ($33.5M)
3,987,332 $ARB ($4.06M)
591,441 $OP ($1.03M)
1,111,926 $DAI
- The most affected chain is Arbitrum ($19.8M), followed by Optimism ($15.3M) and Ethereum ($7.45M).
👉 Exploiter's addresses: https://platform.spotonchain.ai/entity/1587
🚨 BREAKING: $117M in assets stolen from @Balancer in the last 2 hours after a major hack!!!
🔹 Assets stolen are across multiple chains: #Ethereum, #Base, #Optimism, #Sonic, #Polygon, #Berachain – mainly in Liquid Staking Tokens (LSTs) of $ETH.
Top 5 stolen assets:
• 7,838 $WETH (~$29.1M)
• 6,841 $OSETH (~$26.8M)
• 4,459 $WSTETH (~$20.1M)
• 2,405 $SFRXETH (~$10M)
• 2,038 $RSETH (~$8.67M)
🔹 The hacker is acting quickly: Converting LSTs into $ETH in real-time!
🔹 Big move: Whale account 0x009, dormant for 3 YEARS, just resurfaced after the exploit and withdrew $7.38M worth of assets from #Balancer!
⚠️ ALERT: If you’re still on #Balancer, secure your funds NOW before it’s too late! 🔐
Follow @spotonchain for more updates about the hack!
https://x.com/spotonchain/status/1985289043383300351
✉️ Nomis x EYWA Protocol: Real utilities for the real DeFi guys
Meet EYWA Reputation Score: Prove Your Cross-Сhain Activity and Be Eligible For the Airdrop
SCORE YOUR WALLET TO START FARMING
We've partnered with EYWA, the cross-chain trading powerhouse that aggregates Curve Finance pools, to ensure airdrops go where they're earned—right to real degens like YOU 🫵
🖥HOW TO GET STARTED:
1. Visit THE SCORE PAGE to get your Score
2. Go to THE SWAP PAGE
3. Make cross-chain swaps using EYWA and farm extra points
4. Check your total points HERE
5. Wait for the airdrop date to be revealed!
🔝 In the meantime, make more swaps, increase your EYWA Score, and farm points!
➡️HOW TO BOOST YOUR SCORE:
Make swaps across #Ethereum, #Optimism, #BSC, #Polygon, #Fantom, #Arbitrum, and #Avalanche
The higher swaps volume, the higher your Score!
➡️HOW TO GET MORE POINTS:
The higher your Score, the bigger rewards!
🚨 EXTRA REWARDS TIPS:
• Score < 60: Earn 15 points per Score
• Score 60-80: Earn 18 points per Score
• Score 80+: Earn 20 points per Score (max 2000 points)
It seems like we've covered all the questions 🧐 Missed anything? Reach out in the comments!
And now...
Get in, Get yours, LFG⚡️
🚀 Optimism Enhances Wallet Execution Permissions on OP Mainnet
Optimism has introduced a new feature allowing agents and decentralized applications to request wallet execution permissions on the OP Mainnet. According to NS3.AI, this update enables MetaMask to let developers request these permissions using the ERC-7715 standard. This advancement provides Optimism applications with more detailed permission frameworks, moving beyond simple transaction approvals.
#Optimism#WalletExecution#OPMainnet#MetaMask#ERC7715#DecentralizedApplications#Blockchain#Crypto
🔥New Blockchains are Now Supported on SLEX Exchange! 🚀
🥳We're excited to announce that now you can engage with a diverse range of ecosystems as we've added support for:
🔗Scroll
🔗Zora
🔗Arbitrum
🔗Optimism
🔗zkSync
🔗Linea
🔗Base
☄️Now you have more trading flexibility, access to a wider range of tokens, and enhanced opportunities to boost your earnings on SLEX Exchange.
🤝Join SLEX Exchange, deposit your account and use various of blockchains and trading strategies to boost your portfolio:
slex.io/registration
#SLEXExchange#BlockchainSupport#CryptoDiversity#Scroll#Zora#Arbitrum#Optimism#zkSync#Linea
🚀 Scroll Users Face Excessive Transaction Fees Due to Multiplier Increases
Scroll users incurred over $50,000 in additional transaction fees following six manual multiplier increases that elevated Layer 1 data charges to 1,280 times the original baseline. According to NS3.AI, L2BEAT reported that approximately 139,000 transactions were impacted over a span of roughly four days, with the baseline cost estimated at around $280. On April 9, the team reduced both multipliers by 160 times. Etherfi Cash bots contributed approximately $35,000 of the excess fees during etherfi's migration to Optimism.
#Scroll#TransactionFees#MultiplierIncrease#Layer1#L2BEAT#NS3AI#Etherfi#Optimism#Crypto#Blockchain#SCR