Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
⚠️ ATTENTION ATTENTION! ⚠️
Gamety's very first X Podcast is here! 😮
We've been talking about #Gamety for some time. But some of you may still be wondering: "What is Gamety?" 😃
Set a reminder on your calendar!
Time: May 22, 2024, at 3 PM CET.
Venue: X Space
It's time to find out about us! 📈
Tweet 🔗:
https://x.com/gametyio/status/1792968517047988521
🖇 Important Links:
Website | X | Chat | Discord | Announcement | Youtube
For those of you who love engaging with Gamety's social media channels, we have a token of appreciation for you!
Join our Post-To-Airdrop program for a chance to win big from our massive 5,000,000 $GTY token pool! 💰
To participate:
1️⃣ Repost our announcement with #Gamety; @gametyio; and $GTY
2️⃣ Follow @gametyio
3️⃣ Promote for max engagement
More reach = Higher rank on @keani_gg Leaderboard!
Read more: https://keani.gg/gamety
Tweet 🔗:
https://x.com/gametyio/status/1789481845626667017?s=46
🖇 Important Links:
Website | X | Chat | Discord | Announcement | Youtube
👊Punch-to-Earn Airdrop👊
🏅Airdrop Prize Pool: 8,000,000 $GTY
Link: t.me/GametyApp_bot
Calling all gamers!
Who loves to punch someone in the face and earn some money from it?.👊💥
Inspired by the success story of @thenotcoin, Gamety brings tap gaming to the next level!
Invite friends to #Gamety's Telegram, rack up points & climb the leaderboard NOW! 🏆
🔗Tweet:
https://x.com/gametyio/status/1788666261288763550?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Bitcoin halving has been finally took place, cutting mining rewards to 3.125 BTC .
The new era of Bitcoin is starting, and #Gamety is here to ride the wave!
🔗 Tweet:
https://x.com/gametyio/status/1781498935594622998?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
🎉 We're thrilled to announce our partnership with MetaMuffin!🚀
As KOLs in the Web3 space, they'll be helping us spread the word about #Gamety's revolutionary gaming platform on Runes Protocol
Join us on this exciting journey together! 🕹✨
🔗 Tweet:
https://x.com/gametyio/status/1781371957512171916?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Innovation is at the heart of #Gamety’s P2E model.
Explore our cutting-edge game mechanics that redefine entertainment. 🕹️
Be our early members by joining our community now!
🔗 Tweet:
https://x.com/gametyio/status/1780368302159901131?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Learning meets leisure at #Gamety.
We're discussing educational content in Gamety’s socials to enrich our gaming ecosystem. 📚
What Web3 concept would you like to learn with us? 👀
Join our community to find out more!
🔗 Tweet:
https://x.com/gametyio/status/1779933725146640751?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
The #Gamety marketplace is where gaming meets commerce.
Trade in-game assets with ease and security on our platform. 🛍️
Let’s get your way to the top!
🔗 Tweet:
https://x.com/gametyio/status/1779575482679525580?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
🌙 Eid Mubarak to all celebrating around the world!
May this special day bring peace, happiness, and prosperity to everyone.
From #Gamety, with love 💕
🔗 Tweet:
https://x.com/gametyio/status/1778046881060503747
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Tokens that do more!
Find out how $GTY fuels the #Gamety ecosystem, powering rewards, and in-game purchases.
Join our community to learn more!
🔗 Tweet:
https://twitter.com/gametyio/status/1777453037226991772?t=y7r0-4TMHMOkDvjPyXEolg&s=19
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
At #Gamety, every pixel is crafted with the player in mind. 😎
Want to be involved more as early members?
Our user-centric approach will be setting new standards in gaming experience! 🔲
Join our community now! 🚀
🔗 Tweet:
https://x.com/gametyio/status/1777063704519180769
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
It is our pleasure to announce the DCI Capital as one of our investors in the Private Round! 🚀
Together, we can develop #Gamety as the revolutionary gaming platform for Bitcoin ecosystem! 🔲
🔗Twitter
https://x.com/gametyio/status/1775574940139581593?s=20
🖇Important Links:
Website | X | Chat | Announcement | Youtube