Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Лето в разгаре, и мы решили:
Почему бы не раздать то, что вы любите больше всего?
FRHT #GIVEAWAY
Разыгрываем 10 футболок из новой коллекции FRHT 🔥
Условие участия простое — Подписаться на этот канал 🏁
*если ещё не с нами
Мы случайным образом выберем 10 победителей и отправим выбранные футболки
Итоги 25 июля. Поехали 🚀
🎉Bitget Wallet x All At Once #Giveaway🎉
🕙Event duration: August 23 - August 30, 2024
💰Rewards:
🚀$3,000 worth of TON for 300 lucky participants🚀
5M xAAO prize pool is shared equally among all participants
How to join:
1️⃣ Follow @BitgetWallet + @AAO_Game
2️⃣ Join the AAO & Bitget Wallet Telegram groups:
3️⃣ Join the All At Once Bot and complete one game battle
4️⃣ Fill out the Google form to receive your reward
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
🚀 Material Widgets - Everything is Now Available.
Grab it today 👉✨ Special Launch Offer
https://play.google.com/store/apps/details?id=com.jndapp.material.widgets.pack
🎁#Giveaway 15 Promo Codes
♥️, repost, and comment to Participate.
Join Giveaway
🔥
💝GAMEWTB Valentine's Day Giveaway - Steam Gift Card💝
Happy Valentine’s Day!💖 As a token of our appreciation for your continued support, the GAMEWTB TEAM has prepared a special gift🎁 for you.
💸Prize: $5 Steam Gift Card
📅FROM NOW - FEB 17, 2025
=How to Participate=
📲Follow our X: x.com/PC_Gamewtb
❤️♻️LIKE & RETWEET THIS POST☝️
⏰Winner will be announced on Feb 17th
✅COMMENT "DONE" UNDER THIS POST☝️
👀Wait our DM💌
Limited Time Event – Don’t Miss Out!
🤩Whether you're spending Valentine’s Day solo or with a special someone, remember to love yourself! GAMEWTB will keep bringing you the latest game news and exciting events.
Join Gamewtb Group for GIVEAWAYS!
#GIVEAWAY
💚🍀🌱 FARMERS, LISTEN UP! 💎✨
One of the LAST chances to grab OG role 🎖 and it’s about to go CRAZY 😤🔥
We're dropping a massive GIVEAWAY 🎁 /w 30 winners
EACH GETS 0.1 SOL 🤑 + OG 👑
How to join:
1. Join our X (Twitter)
https://x.com/ggpweb3
2. Join our Discord
https://discord.gg/gg-paradise
3. Leave wallet in #giveaway channel
4. Stay active on server
Results in Friday 🕶
Let’s make it loud before the farm goes wild 🌿🚀
💥500 QUACK AI NFTs and 200,000 QUACK Points Giveaway to TokenPocket users!
👉https://app.galxe.com/quest/TokenPocket/GC6YCtmDkS
🍾500 lucky winners will each receive a QUACK AI NFT!
🎯 Winners will also be eligible to earn an extra 400 points by interacting with the QUACK AI platform.
#giveaway
💧Airdrop : Lifestory💧
📣Complete Task: ➕ $6000 #Giveaway - 4 Days contest
🏆Winners: For All Valid Users
📅End date: After 4 Days
💎Ratings: ⭐️⭐️⭐️
🔛Galaxy Airdrop Gleam Click Here🔛
🌀 Follow on Twitter and retweet the pinned post.
🌀 After Done Airdrop Task then Create your wallet.
📡Enter your information to the Airdrop Gleam.
🗞Note: All airdrop steps should be completed.
⛵️Business Inquiry: Admin || Admin2
💥Big Congrats!
🏆Check if you are on the ZoomManor #Giveaway Winner List!
👉https://docs.google.com/spreadsheets/d/1QQ1rdc3jnt6BAhWL_8qhJJe56KyxSqF8BvCk21dLvSk/edit#gid=0
🎁The rewards will be distributed by ZoomManor before Jan 5th. ZoomManor
💙Thank you all very much for your participation!
If you have any questions, you can join TokenPocket's Telegram to get more info.
👉https://t.me/tokenPocket_en
🪂New airdrop: FOBOCLUB x MEXCGlobal Collab Event #giveaway
💰Reward: 50 FOBO CLUB WLs (NFT)
📅Distribution: uncertain
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!
🪂Airdrop: Mystery Box #Giveaway
💰Reward: $3,000
👨💼 Winner: All participants
📅 TIME:10/03/2022 07:00 AM - 10/09/2022 11:00 PM UTC
🔗Airdrop Link: airdrop page
🔹Complete all tasks of the airdrop
Disclaimer: Airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!