Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Upcoming Airdrops Alert! 🚀
Hey everyone! 🎉 If you missed out on the Dogs airdrop, don’t worry! There are some exciting new airdrops coming up that you won’t want to miss. Check out these potential big earners:
1. Major🌟
1. X Empire 🏰
3. Cats🐈
4. Memefi🎭
-Confirmed Listing Date: October 9th
-All WILL BE LISTED IN ABOUT A MONTH TIME , SO JOIN AND GET FREE TOKENS BEFORE ITS TOO LATE!!!
#Airdrops
🎁 The #giveaway with 4EVERLAND has officially ended! A big thank you to #TokenPocket for their support and to all participants.
👇🏻Keep an eye out for upcoming thrilling #airdrops and don't forget to claim your $4EVER points at: https://dashboard.4everland.org/quest/tp
🥳We are thrilled to announce that UXLINK has made strategic partnership with @LumozOrg
to build Social Growth Layer(SGL) together!
Our ecosystem fund @UFLY_Labs
will invest @LumozOrg and we will empower Lumoz social growth & business development globally especially in Japan and Korea market & community.
💰Lumoz native token $MOZ will be #TGE on CEXs soon and we will make ONE MILLION dollar value #Airdrops to qualified $UXLINK holders and stakers!
Lumoz is the leading Modular Compute Layer for ZK & AI. Lumoz uses PoW mining mechanism to provide computing power for Rollup, ZK-ML and ZKP verification.
Please stay tuned for our updates!❤️
Channel: Legit Airdrop ️
Members: ~142.24K
💢 Username: @legit365airdropss
Description:
Welcome dear subscribers! We will do our best to share the legit airdrop campaigns timely. If You Need Any Airdrop Project Promotion Then Contract here @Legit365airdrop1 Buy ads: https://telega.io/c/legit365airdropss
🏷 Tags: #airdrop
#airdrops#cryptocurrency
https://telegramchannels.me/channels/legit365airdropss
$ORB and $MOZ #Airdrops done just now, #UXLINKseason2 stakers please kindly check your wallet address to get the token❤️https://arbiscan.io/address/0x0698e377ca9dbfb5c77503d611c6f1f38cf46ba2
#Airdrops Are Making Millionaires In Crypto – Here’s How [Full Guide Cosmos, LUNA & More]
#cryptogemtokenshttps://cryptogemtokens.com/airdrops-are-making-millionaires-in-crypto-heres-how-full-guide-cosmos-luna-more/
Phantom Wallet Dismisses Token Rumors
Phantom Wallet team clarifies: no plans for a native token or airdrop. Focus remains on improving the token and app discovery mechanism. More details: Read here
#Phantom#airdrops#wallets#Crypto#VC