Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
#Web3Festival in Hong Kong wrapped up during a tough week for the crypto market, but builder momentum was high and the community remains active 🔥
Announcements such as TON Blockchain's TON wallet expanding into the U.S. and events hosted by Monad and BNB Chain indicate that the space is still moving forward.
For a recap on highlights from this past week, read the DWF Ventures team's summary here.
DWF Ventures continues to support teams building through every cycle. If you're working on something, get in touch: https://www.dwf-labs.com/ventures
During our week at #Web3Festival in Hong Kong, Eugene Ng, Founding Partner of DWF Labs, gave a talk on the mainstage about the newest trends and narratives in Web3 innovations.
He discussed the rise of Bitcoin ecosystems, the institutionalisation of crypto as an asset class; memecoins, AI and more. 💥
Missed his speech? Check out the livestream recap.
#Web3Festival was a successful week, and we especially enjoyed our side event, DWF Labs Haus, on Sunday night. 🌙
It was an evening of delicious cocktails and canapés, fantastic company, and insightful conversations. Thank you to everyone who came!
During #Web3Festival Hong Kong, our team was able to share insights about innovations that are heating up in the crypto space. 🔥
Yesterday, Fiona Ma, Senior Associate at DWF Ventures, gave a speech about decoding the Ethereum restaking landscape, delving into the evolution from staking to restaking.
Restaking is one of the verticals DWF Ventures is highly interested in - if you're a project innovating in multiple sectors, feel free to reach out to their team on X!
Our team had an amazing time at #Web3Festival in Hong Kong!
It was our second year sponsoring Web3 Festival, and this year was even bigger and better than the last. 🔥
It was a pleasure to meet our friends and partners in person at our booth. Thank you to everyone who came by!
About last night... 👀
That's a wrap on our event, DWF Labs Haus, during #Web3Festival Hong Kong. 🔥
Meeting industry leaders, founders, and innovators in person is always a pleasure as we continue to work from a diverse network of cities and countries worldwide.
Thank you to everyone who attended, it was great to meet you all!
Setting up for our DWF Labs Haus event during #Web3Festival, which kicks off at 6 PM. 👀
We're in full swing gearing up to host an unforgettable evening filled with incredible networking opportunities and delicious cocktails and canapés.
Looking forward to meeting everyone soon!
The teaser for Hong Kong #Web3Festival 2024 just dropped!
We're excited to be Title Sponsors of this event ✨
Get ready for this spectacular gathering of #Web3 set for April 6-9 🔥
Get February offer: https://lu.ma/hkweb3festival2024
🌎TONCA$H Travel Cashback is ON!
Planning to hit Hong Kong #Web3Festival or Dubai #Token2049? Why not earn cashback in $BTC, $TON, or $USDT when booking your trip?
Hot Deals:
⚡️ 10% cashback on flights🛬
⚡️ 20% cashback on hotels📍
How to Claim?
✅ Book your trip via TONCash App
✅ Receive your cashback in $BTC, $TON, or $USDT directly in your wallet! T&Cs apply
💵Get Your Place Now!🏝
#TONCash#Travel#Web3#HongKongWeb3Festival#DubaiToken2049#Cashback