Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🤝Electra Weekly PnL Challenge
For only 7 days — from March 24 to 31,#Electra is holding a large-scale trading challenge, where everyone can compete for cash prizes and airdrop points!
Participation is automatic — Ranking by net PnL in USDT, just trade and monitor your PnL. Top 10 traders will be rewarded.
💵Prize pool in USDT:
•1st place – $250
•2nd place – $200
•3rd place – $150
•4th place – $100
•5-10 places – $50 each
Additionally : for every $10M of trading volume, the prize pool increases by $100!
⚡️1,000,000Airdrop points
• Top 1: 75,000 Points
• Top 2–10: 35,000 Points each
• Top 11–50: 11,250 Points each
• Top 51–100: 3,200 Points each
📈 You can follow the leaderboard and your position on the Leaderboard page
🚀Trade directly from Telegram!
#Electra#Trading#DEX#DeFi#PnL
🌱TONCO: new level of convenience + prizes from TEC Team!
Updates that make your work easier🙂
💱Zaps function– automatic exchange of coins before entering the pool. For example, you can now replenish the liquid pool with only one token, the system will automatically divide it into the required proportions and balance the pair. No more fuss with exchanges before setting liquidity.
Also in this update:
🟢 Instant update of data on #APR, #PnL, #ROI and position lifetime.
🟢 Profit/loss taking into account the exchange rate is always before your eyes.
🟢 You can model the boundaries of a position and see the expected income.
🟢 Improved UI and bugs fixed.
🤟Meanwhile, APR in the TON/USDT pair is ~75%🔥
🪙Joint action TONCO x TEC Team! Prize fund 100,000 points , winners will receive 5,000 coins each. The previous activity brought participants 💵100 in a couple of clicks. Don't miss out!
TONCO | Channel | Chat
✨ DAR UN FEEDBACK es muy importante, para evitar posibles reacciones malhumoradas 🤬, usa la técnica del sandwich 🥪
✨ Consiste en tres pasos:
- Decir primero algo positivo 🔝🔝 de la persona, especialmente destacable.
- Realizar el comentario sobre el aspecto a mejorar o corregir, que generalmente se toma como negativo.
- Acabar dando una nota positiva 🆒 sobre ella.
✨ De esta manera la comunicación 📣 se torna más amable y asertiva.
#comunicación#feedback#lenguaje
#asertividad#coaching#pnl
#Romania🇷🇴
#Presidenziali
Crin #Antonescu, 65 anni e già docente di storia, è originario di Tulcea (Dobrugia). È stato Presidente del Senato rumeno dal 2012 al 2014 (e Presidente ad interim della Romania nel 2012), nonché Presidente del Partito Nazionale Liberale (#PNL|PPE) dal 2009 al 2014. È stato più volte deputato e senatore. È attualmente indipendente, ma rappresenta il candidato della coalizione elettorale "Romania Avanti" (ro. România Înainte), che include il Partito Social Democratico (#PSD|S&D), il Partito Nazionale Liberale e l'Unione Democratica Magiara di Romania (#UDMR|PPE), ovvero i partiti che sostengono l'attuale governo guidato da Marcel #Ciolacu (PSD).
@TuttoElezioni
#Romania🇷🇴
#Presidenziali
Victor #Ponta, 52 anni, è originario di Bucarest (Muntenia). Avvocato di professione, è stato deputati dal 2004 al 2020, Presidente del Partito Social Democratico (#PSD|S&D) dal 2010 al 2015, è Primo Ministro dal 2012 al 2015. Attualmente è di nuovo deputato, come indipendente nel gruppo parlamentare del PSD. Ponta si candidò anche alle elezioni presidenziali del 2014, dove giunse al ballottaggio con Klaus #Iohannis, sostenuto dal Partito Nazionale Liberale (#PNL|PPE); in quella tornata Ponta venne sconfitto da Iohannis. La sua candidatura è sostenuta da diversi partiti minori, tra i quali PRO Romania (#PRO|S&D), di cui è stato Presidente dal 2018 al 2024.
@TuttoElezioni