Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
❓Do you want to build a #dApp on Venom❓
✅ Join the VenomBlockchain dev community on Discord
➡️https://discord.gg/E5JdCbFFW7
🔎 Check Venom docs with development guides for smartcontracts, tokens, NFT, and more
➡️https://docs.venom.foundation/build/development-guides
⚡️TON Community: MyTonWallet v3.6 Features Unveiled
#TON#Dapp
The TON Community introduces MyTonWallet v3.6 with significant updates. Users can now track any wallet address and view $TON activity within the app, and share transfer links before confirmation. Discover new features like Remember Passcode and Dapp Action Previews.
Source: link
@tonlines
🆕We just released TokenPocket's new version on iOS. 🔺2.4.8🔺
🔵Support Boost Mode. 🚀#memecoin
🔵Native support for #DApp Content Translation.
🔵Native support for TRON Batch Transfer.
You can now upgrade your TokenPocket on the App Store. Ensure the developer is 'TP Global Ltd'.
🔗https://tokenpocket.pro
🆘 Просто эпический фейл от WalletConnect, который я обнаружил сегодня утром.
#WalletConnect - крупнейший (и возможно единственный) сервис подключения крипто кошельков к #dapp#web3 приложениям внес Украину и РФ в черный список.
По сути это парализует работу всего DeFi для СНГ. Вот такая децентрализация или иначе - отсутствие альтернатив “не из США”!
🍌
30 million users in Bitget Wallet!🌐
Bitget Wallet is a cutting-edge Web3 multi-chain wallet that offers a comprehensive platform with wallet, exchange, NFT marketplace, DApp browser, and Launchpad features. Supporting over 100 public blockchains, Bitget Wallet aggregates top DEXs and NFT markets to provide users with the best trading prices.
Bitget Wallet's mission is to create a world-class decentralized crypto wallet that provides a secure and convenient trading experience for all crypto enthusiasts.
Since its founding in May 2018, Bitget Global Inc. has been providing secure asset storage, fast trading, exchange, and investment in DeFi to over 30 million users worldwide. Now it is not just a wallet but an entire ecosystem that provides access to various activities and airdrops.
Tomarket Airdrop
Bitget On Chain Fund Invests in Tomarket App, Fast-Growing Web3 Game on TON. Airdrop scheduled for September.
Join the farming and get 2,000 🍅 $TOMATO tokens at the start!
Download Bitget Walletand start your Web3 journey now!🚀💎
#BitgetWallet#Web3#NFT#TON#DApp#DEX
🆕 0xMantle Bridge now fully supports TokenPocket login, and the official bridge is also listed on the TokenPocket #Mantle Hot #DApp List!
👉https://bridge.mantle.xyz/
🔥You can access Mantle Bridge with your TokenPocket wallet and enjoy the #MantleJourney!
👉https://extension.tokenpocket.pro/#/
👉https://www.tokenpocket.pro/en/download/app
#TokenPocket#MantleJourney
【Details】https://twitter.com/TokenPocket_TP/status/1711686131371413918
【Powered By】Crypto Box
🆕 Mantle Bridge now fully supports TokenPocket login, and the official bridge is also listed on the TokenPocket #Mantle Hot #DApp List!
🔥You can access Mantle Bridge with your TokenPocket wallet and enjoy the #MantleJourney!
👉https://extension.tokenpocket.pro/#/
👉https://www.tokenpocket.pro/en/download/app
#TokenPocket#MantleJourney
【Details】https://twitter.com/TokenPocket_TP/status/1711685010049368156
【Powered By】Crypto Box
😼Catizen Mini Game Center Open Beta now LIVE!🚀🎮
👌 Dive into a world of top-tier games that blend fun with innovative earning opportunities. Enjoy exclusive rewards like game airdrops and referral bonuses.
👌 Earn a 10% top-up rebate from all your referrals across all games, including Catizen!
Don’t miss out — start your adventure in the Catizen Mini Game Center today! 🌟
🔡
🔡
🔡 Open beta is live! Report bugs or game feedback to earn 300 Catizen FishCoins 🪙
😸Explore Catizen Mini Game Center
#catizen#gamee#play#p2e#web3#gamefi#dogs#telegram#dapp#notcon#hamsetr