Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🔥 Baby Slerf Airdrop Event
🎁 Total Airdrop Pool 1,000,000,000 $BSLERF
✅ Complete #gleam
https://gleam.io/BZTdD/baby-slerf-airdrop-event
Disclaimer: Please do your own research before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop free!
🔥 Acti Airdrop Event
🎁 100 $ACTI For ALL
✅ Complete #gleam
https://gleam.io/GLdfR/joinactiqsocialmedianew
Disclaimer: Please do your own research before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop free!
📣 BitCraft Airdrop is live!
🏆 Reward for Tasks: 175 $BLOCK for 2000 random participants each.
👨👩👧 Referral Reward:50,000 $BLOCK for top 50 referrers.
✅ Complete #gleam
https://gleam.io/competitions/tZm7C-bitcraft-airdrop
Disclaimer: Please do your own research before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!
🔥 MetaOasis Momo Airdrop
🚀 Airdrop link : https://t.me/MomoAI_bot/app?startapp=0KHBIB
💳 Wallet : Solana-Ton
💬 What needs to be done: Go to Draw, send it to someone 1 time and then draw!
🚨I ask you to do it, it may be important.
#Airdrop#gleam
🙎♂️$10,000 Bombie Giveaway on Gleam
This activity will be very useful for everyone who plays Bombie. All you need to do is subscribe to Bombie's TG and Twitter. You will also need the Bombie UID — it is behind the avatar on the left bottom corner.
🎁200 Random Winners Will Share $3,000 in $TON
🛷3,000 Random Winners Will Share $7,000 In-Game BTC and Airdrop Boxes
Follow the instructions to earn points. The more points you earn, the more chances you have to win prizes!
‼️ Make sure your #Twitter account has a profile photo, otherwise it will be flagged as a spam.
Deadline: December 20, 00:00 (UTC+8)
#TON#Bombie#Gleam#airdrop
🙎♂️$10,000 Bombie Giveaway on Gleam
This activity will be very useful for everyone who plays Bombie. All you need to do is subscribe to Bombie's TG and Twitter. You will also need the Bombie UID — it is behind the avatar on the left bottom corner.
🎁200 Random Winners Will Share $3,000 in $TON
🛷3,000 Random Winners Will Share $7,000 In-Game BTC and Airdrop Boxes
Follow the instructions to earn points. The more points you earn, the more chances you have to win prizes!
‼️ Make sure your #Twitter account has a profile photo, otherwise it will be flagged as a spam.
Deadline: December 20, 00:00 (UTC+8)
#TON#Bombie#Gleam#airdrop
🔥 Emartzon Airdrop Event 🪂
🎁 Total Airdrop Pool $10,200 Worth $EMZ For 2000 Random Users and Top 20 Referral
✅ Complete #gleam
gleam.io/2Ebgn/emartzon…
Emartzon aims to revolutionize the world of ecommerce! emartzon.com
#Airdrops#Giveaway#crypto#airdrop
Disclaimer: Please do your own research before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!
🔥DBMETA Halloween Airdrop Event
1,000,000 DB For 2000 Random winners
✅ Complete #gleam
https://gleam.io/cUrnm/db-meta-halloween-campaign
#airdrop#airdrops#crypto#airdropcrypto
🔥 Archloot Airdrop
🚀 Participation link : https://wn.nr/v2SA5Qx
🏆 Winner: 250
💰 Prize: $3000 $ALT
💳 Wallet: Metamask
🚨 Last Day: January 25th
Distribution: January 28
💬 Groups You Should Join :
https://t.me/archloot
#Airdrop#Giveaway#Gleam#Archloot
🔥 Dogex AI Airdrop Event
🎁 Total Airdrop Pool $4200 Worth $DOGEXAI
✅ Complete #gleam
https://gleam.io/NKCf2/dogex-ai-airdrop-event
#Airdrops#Giveaway#crypto#airdropcrypto#airdrop
Disclaimer: Please do your own research before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop free!