Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🆕We've released a new version of TokenPocket on Android.
🔺2.7.0🔺
🔵Support EIP-7702-based Dust Cleaner function.
🔵Optimize the trading experience.
🔵Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website. 🔗https://tp.xyz
🆕We've released a new version of TokenPocket on Android. 🔺2.6.0🔺
🔵Fully upgrade the trading experience.
🔵Add PnL analysis on the Asset page.
🔵Enhance the market page with more comprehensive data display.
🔵Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website. 🔗https://tp.xyz
🆕We released TokenPocket's new version on Android. 🔺2.4.7🔺
🔵Upgrade the wallet security backup feature.
🔵Support EIP-4527 Protocol.
🔵Meme Mode supports TRON network.
🔵Add security reminders for custom nodes.
🔵Support the Notifications for Multi-Sig wallet transactions.
🔵Optimize token search functionality on the Asset page.
🔵Optimize the experience on the Solana network.
🔵Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website.
🔗https://tp.xyz
🆕⛓svmBNB is now live on TokenPocket.
svmBNB is a high-performance SVM chain developed by the SOON team for BNB Chain, based on the SOON Stack.
💙How to create/import a svmBNB wallet on #TokenPocket?
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/svmbnb
🎈Discover the svmBNB Ecosystem with Your TokenPocket!
📱https://tp.xyz
💻https://extension.tokenpocket.pro
📣 Our New Official Website: https://www.tp.xyz/🌐
It will operate alongside http://tokenpocket.pro to provide users with a more stable and efficient access experience.
A smarter, easier way to explore Web3. #TokenPocket
👉https://www.tp.xyz/
👉https://www.tokenpocket.pro/
🆕We released TokenPocket's new version on Android and iOS.
🔺Android: 2.4.5
🔺iOS: 2.6.6
🔖Details 👇
🔵Support BEP-414, enabling users to pay $USDT or other tokens as gas costs.
@BNBCHAIN
🔵Support the PnL display on the Market page.
🔵Support MEV Node Detection service.
🔵Support deleting the wallet address on Recent Transfer.
🔵Support for Smart Address tagging.
🔵Update the default token icons.
🔵Optimize the Secret Recovery Phrase backup process.
🔵Optimize the wallet synchronization feature.
🔵Optimize Market data display.
🔵Optimize the wallet service on Solana and TON.
📱You can upgrade your #TokenPocket via Google Play, App Store, or the official website.
🔗https://tokenpocket.pro
🆕Eclipse is now live on TokenPocket.
Eclipse Mainnet is Ethereum's first Solana Virtual Machine (SVM) network. Eclipse Mainnet combines the best pieces of the modular stack.
💙How to create/import an Eclipse wallet on #TokenPocket?
Guide 👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/eclipse
🎈Discover the Eclipse Ecosystem with Your TokenPocket!
👉https://tokenpocket.pro
🆕We released TokenPocket's new version on Android and iOS.
🔺Android: 2.4.3
🔺iOS: 2.6.1
🔵Market and Trading Sections Upgraded.
🔵Meme Mode supports BNBCHAIN and Base.
You can upgrade your #TokenPocket via Google Play, App Store, or the official website.
🔗https://tokenpocket.pro
🆕 SOON is now live on TokenPocket.
SOON is a high-performance SVM Rollup designed to realize the Super Adoption Stack.
💙How to create/import a SOON wallet on #TokenPocket?
Guide👉https://help.tokenpocket.pro/en/wallet-operation/how-to-create-a-wallet/soon
🎈Discover the SOON SVM Ecosystem with Your TokenPocket!
👉https://tokenpocket.pro
2024: Moving Forward with Our Users, In Tune with the Market! 🌊
Thank you for all the support in 2024! Let’s continue growing stronger together with TokenPocket!💙
Dive into the #TokenPocket 2024 Annual Report ⤵️
https://tokenpocket-gm.medium.com/f01689f88a91
🔵New Bridge Integration on the #TokenPocket Trade page: SwapKit
🎯 Redefining Cross-Chain Bridging with TokenPocket!
SwapKit delivers an innovative cross-chain bridging solution, fully integrated into TokenPocket, making it easier than ever to swap cross-chain between Native $BTC, $USDT, $USDC, $ETH, and other leading chains and trending tokens.
Make cross-chain bridging easier than ever.
📱https://tokenpocket.pro
💻https://swap.transit.finance/?locale=en&market=1&inputChain=BTC&inputSymbol=BTC&outputChain=ETH&outputSymbol=ETH#/
🆕We released TokenPocket's new version on Android. 🔺2.4.0🔺
🔵 Support Swap & Bridge on the SuiNetwork.
🔵 Support SuiNetwork cold wallet and watch-only wallet features.
🔵 Support custom network sorting functionality.
🔵 Optimize the Transfer page.
🔵 Optimize users’ experience.
You can upgrade your #TokenPocket via Google Play or the official website.
🔗https://tokenpocket.pro