Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Lookonchain | ꘜ
BTC just broke through $124,000, setting a new all-time high!
If you bought #Bitcoin every day like the El Salvador government, you'd have a 115% return!
Since Nov 18, 2022, El Salvador has been buying 1 $BTC per day — buying 1,000 $BTC(cost $57.29M, now worth $124M) at an average price of $57,793, with an unrealized profit of $66M(+115%).
https://intel.arkm.com/explorer/entity/el-salvador
An Satoshi-era #Bitcoin OG moved 1,000 $BTC worth $74.03M to 2 newly created wallets and is likely preparing to sell.
The wallet still holds 1,833 $BTC worth $135.6M.
https://intel.arkm.com/explorer/address/bc1qczar85zjppfjr8df8qnc4l3h5r957v6p2udryz
https://x.com/OnchainLens/status/2044355669982380083
Follow @OnchainLens for more Onchain Updates.
Erik Voorhees(@ErikVoorhees), an early #Bitcoin supporter and founder of ShapeShift, is buying back $ETH after a one-year break.
One year ago, he sold 12,886 $ETH($42.83M) at $3,324.
In the past 5 days, he has spent 17.75M $USDT to buy back 8,576 $ETH at $2,069.
He still holds 26.77M $USDT and may buy more $ETH.
https://intel.arkm.com/explorer/address/0x431dcE06f8A098C6f70CA6CecdCa87281eF10c91
Charles Schwab increased his position in the financial company Strategy $MSTR of #Bitcoin by 91,559 to 1.27 million shares ($168 million).
Charles Schwab, who oversees trillions in client assets, increased his position in Strategy ($MSTR) by 91,859 shares, raising his total holdings to 1.27 million shares worth around $168 million.
Strategy is widely known for its large Bitcoin treasury strategy, making MSTR an important proxy vehicle for institutional engagement in Bitcoin via traditional stock markets.
Analysts say that Schwab's increased allocation reflects the ongoing institutional confidence in Bitcoin-related stocks and reinforces a deeper integration between traditional finance and digital asset-based corporate strategies.
🥳@Runlifenick_fx✅
🐱🙏🐶🚨
Michael Saylor says, “You’ve got 10 years for the digital gold rush, you should get your #Bitcoin before there’s no more Bitcoin for you.” 🤯
🌍t.me/Runlifenick_fx✅
BULLISH: 🟠 Billionaire Michael Saylor says $1 million #Bitcoin price is inevitable.
“It will grow from $2 trillion to 20 trillion to $200 trillion” 🚀
Source: @Runlifenick_fx✅