Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🪂Airdrop ~ Shiba Inu (SHIB)
💲Reward: 150 Million #Shiba inu
💎 Presents Ratings: ⭐️⭐️⭐️
👑Winners: 1,000 Lucky winners
➡️ Airdrop Page For Coingabbar
📚 How to Join Airdrop?
↪️ Signup at Coingabbar & Verify your Email to get 100k Cubs
↪️ Submit earned cubs for conversation, (1 Cub = 2 SHIB)
Earn More Cubs
Download the Android App/ IOS App
✏️Notes: Make sure to complete all tasks to receive rewards.
ℹ️Distribution date: Will be announced by the project team after 28t-h January.
Look at #SHIBA now! 💰🔥
Went from2,590%to 4,135%, that's 1,545% extra profit just by holding it a bit more
A nice 41X return from this single Signal⭐
🔸$50 would return $2,060💸
💰$50 would return $1,375💸
Enjoy 4,100% profit🆙. 🤝Congratulations allPremium Members. Now imagine if you followed the rest of the signals.. 🤑💯
We keep printing money, day after day 💯
Don't miss out - join us and start sending those gains to your bank 👇
@Kevindexter✅
💰#SHIBA just smashed
2️⃣
5️⃣
🔠gains!Another big win, no surprise there 😌
It's business as usual - every day, like clockwork, we are in the fast lane, leaving the competition eating our dust 💰💸
We keep printing money, day after day 💯
Don't miss out - join us and start sending those gains to your bank 👇
@Kevindexter✅
🐶 .Shizarium is getting ready for hardcore with a new version of Bor.
🧡The update will add a burning mechanism: 70% of the base fees will be converted into $SHIB tokens and removed from circulation, which may increase their price. The rest of the fees will be used to develop the ecosystem.
💡 And also announced the launch of #Shiba Eternity #Web3.
#SHIBA INU eBAY || THIS COMPANY ACCEPT CRYPTO || GET READY ✌🏻
#cryptogemtokenshttps://cryptogemtokens.com/shiba-inu-ebay-this-company-accept-crypto-get-ready-%e2%9c%8c%f0%9f%8f%bb/
The Perfect Shiba Inu — 中号
Introducing Naka Go, the foundational dog behind this breed’s revival.
$NAKA
CA (Ethereum):
0x956220463DE0e1d7E3D5Da4ab1f8cA15E1e0aB0B
#NAKA#SHIBA#ETH#TSLA#TESLACALLS🐕🚀
💰Bullish on #TRUMP
Short term : $21 - $27
Long term : $48 - $79
The main character of meme world this stage.
If you missed
#Doge 2020 💰/ #Shiba 2021 💰/
#Bonk 2023 💰/ #Pepe 2024 💰,
you are going to miss #Trump 2025 💰
🥸 Above is a 10-year chart of significant #altcoins and the number of non-empty wallets (#hodlers) in the corresponding networks: #Litecoin: 8.08M wallets #Dogecoin: 6.69M wallets #XRP Ledger: 5.24M Wallets #Cardano: 4.48M Wallets #Shiba Inu: 1.39M wallets #Chainlink: 722K wallets
Данные от Santiment: 10 крупнейших кошельков удерживают значительные доли в крупнейших альткоинах, что подчеркивает проблему централизации в крипте:
#Polygon (MATIC): 69.4%
#Shiba Inu (SHIB): 61.2%
#Uniswap (UNI): 50.8%
#Pepe (PEPE): 46.1%
#Ethereum (ETH): 44.0%
#Tether (USDT): 33.1%
#Chainlink (LINK): 31.1%
#Toncoin (TON): 27.5%
#Multi Collateral Dai (DAI): 24.5%
#USD Coin (USDC): 19.0%
💬Мнение : Такая концентрация может повлиять на рынок, так как несколько крупных игроков могут существенно влиять на цену и ликвидность этих активов.
#КриптоНовости#обзоррынка