Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Join us in 20 minutes to explore the meme ecosystem on #BSC with @LordCheems_Bsc & @Testonbsc! 👀
⏰ 1PM UTC+0
📅 Tuesday, February 11th
📍https://x.com/i/spaces/1BdGYqlaOeXGX
🔜 Tune in to our BNB AMA today to learn about #BSC Governance and discover how you can get involved!
⏰ 1PM UTC
📅 Today, October 24th
📍 BNB Chain X, YouTube, & Binance Live
🔗https://youtube.com/watch?v=vmS1TPNKt4s&ab_channel=BNBChain%28Official%29
🚨 The final sunset of BNB Beacon Chain is set for mid-November!
Migrate your assets to #BSC to avoid losses.
Learn about the asset migration process and necessary actions for users and CEXes on the blog below! 👇
https://www.bnbchain.org/en/blog/final-sunset-plan-of-bnb-beacon-chain
🔥🔥🔥LIVE ON 8 SEPTEMBER (9PM GMT+3) 🔥🔥🔥
TIPSY Token #BSC on 🥞PancakeSwap!!!
The First Blockchain-based Adult-Friendly Entertainment Ecosystem.
Tipsy is an app store - and a place where adults have fun!
It's an open-source marketplace for adult entertainment.
It's a platform where developers can create and deploy apps and games, merchants can sell goods and models can upload and share media or offer services such as video chat.
Tipsy is an ecosystem - with interoperability between apps and games
✅Certik Audited
✅Low MC
✅Very Low Circulating Supply
✅Vesting(Double your Tokens)
✅NFT
🚀 CEX Listing
🔗 Virtual Land Sale
❤️ TipsyFans
🌎 TipsyWorld
📞 Telegram: https://t.me/tipsyonline
🌐 Website: tipsyonline.io
🐦 Twitter: twitter.com/TipsyLabs
🎥 YouTube: https://youtu.be/-uBU3s5uSPk
👋
✅ WELLCOME TO ✅
💯$HGT
✅ PRE-SALE COMING
🚨$HGT — backed by more than hype. It’s backed by gold.
👉 From the producing Hellyer Mine in Tasmania 🇦🇺, $HGT gives you exposure to tokenized gold, lead & zinc — all secured by audited reserves.
🌱 Built on #BSC, powered by hydroelectric energy
🔒 Audited reserves. Institutional custody.
🟢 Gold-backed stablecoin launching in Phase2
🔥 Pre-sale COMING — limited allocation, real utility
🕊Twitter
https://x.com/Hellyergold
🔵Telegram
https://t.me/HGTToken
🌐Website
https://hellyertoken.co/
🚀 New Gem 💎 : Daddy Cake
💲 Total Supply: 1,000,000,000,000,000
⏱ End date : Aug 15th, 2021
⏳ Distribution Date : Sep 1st, 2021
🔘 Rate : ⭐️⭐️⭐️⭐️⭐️
🏚 Aidrop :
🔸 Fill in the form with your details:
https://forms.gle/uzEC2Kp33xiySegp7
🔸 Join the Telegram group:
@DaddyCake_Chat
🔸 Join the Telegram channel :
@daddycakechannel
🔸 Buy:
https://pancakeswap.finance/swap?outputCurrency=0x98899de44fdfe52b385fbe53c82042bbbcb8e673
🔸 Follow the Twitter account:
https://twitter.com/daddycake_bsc?s=21
🔸 Retweet our pinned post on your Twitter account & tag 5 friends.
📑Additional Information:
DaddyCake.io - Meme that’s Hyper deflationary with built in smart staking system, hold, pet, love, & save dogs! on #BSC
Contract:
0x98899de44fdfe52b385fbe53c82042bbbcb8e673