Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🌙#Hashtag’chilarim, ulugʻ ayyom - Qurbon hayiti muborak!
🐑 Keltirilayotgan qurbonliklar dargohida qabul boʻlsin.
✈️ Eng yaxshi tilaklar va albatta, eng yangi gadjetlarni tilab qolaman.
😎Hurmat bilan, JM!
Hammaga salom!
Ha, ancha yo'q bo'lib qoldim, postlar qo'yilmadi, ijod qilinmadi. Sabablar yetarlicha, afsuski.
Kuz fasli oilamiz uchun quvonarli kelib, o'g'il farzandli bo'lgandim. Kuz oxiriga kelib esa Otam bilan bog'liq kutilmagan fojea yuz berib, 29-oktyabrda reanimatsiyaga tushib qoldilar. Allohning irodasi ekan, 46 kunlik og'ir betoblikdan keyin Otam 14-dekabr kuni vafot etdilar...
Shu-shu, dafn marosimlari bilan ovora bo'lib, o'zimning sog'ligim va halovat yo'qligi bois kanalga yangilik joylashtira olmadim. Lekin, hayot davom etarkan. O'zimda kuch to'plab, sekin-asta ishga, ijodga qaytyapman. Shu sabab, sizning qo'llab-quvvatlab turishingiz zarur menga.
Rahmatli Otamni sizlarga keyinroq batafsil tanishtirmasam bo'lmaydi. Chunki ular #Hashtag blogimning qandaydir ma'noda asoschisi ham. 6 yoshligimdan qo'limga "payal'nik" berib, tranzistor-u diodlarni, kondensator va rezistorlarni tanishtirgan, birinchi radio, robotlarimni yasashni o'rgatgan aynan Otam - Bekpo'lat o'g'li Faxriddin!
Adamni ohirati obod bo'lsin, Jannatlarda uchrashish nasib etsin. Duolaringizda eslab qo'ysangiz, sizdan minnatdorman. 🤲🏻
⚠️ Endi 9/11 men uchun yomon sana emas!
🎉 Bu xursandchilikni sizlar bilan bo'lishgim keldi. Bugun oilamizda "kichkina #hashtag" dunyoga keldi, Alhamdulillah.
🤲 InshaAllah yurtimizga, dinimizga xizmat qiladigan o'g'il bo'lsin. "Ayti" bo'yicha bilimi kuchli, sportdayam tengsizlar qatorida bo'lib, O'zbekiston bayrog'ini yuqoriga ko'p marotaba ko'tarishini niyat qildim (orada bayrog'imizni Oyga, Marsga qo'yishini ham o'yladim, to'g'risi 😅)
☺️ Oldindan bildiriladigan tilaklar va tabriklar uchun rahmat, #Hashtag oilasi!
🏆 OKX Bounty Hunt New Season #2🏆
Engage, Refer & Win!
Prize:
- $400 USDT weekly allocation
🥇 $80 | 🥈 $60 | 🥉 $40
4th to 6th - $20
7th to 10th - $15
11th - 20th - $10
How to earn points:
✅ Check In Daily -> GM OKX Fam #OKXBountyHuntNewSeason#2 every day 👉50000
✅ Chat & Engage - Chat actively (30+ characters) 👉30
✅ Invite Friends - 🔗 Tag Admins to get your personal invite link and invite more people to join OKX Announcement👉50
✅ Share your reactions/emojis under the announcement posts
Check points🏆
Bounty points
Bounty ranking
More points!
👉 Share pictures and topics of New Year and crypto with the #hashtag in the chat
Join the event now👇👇👇
OKX Bounty Hunt New Season #2 Form
Our Socials:
⚜️Sign Up on OKX | Join Affiliate | TG | DC | Wallet TG | Wallet Announcement | OKX on Spotify | Twitter/X | YouTube
⭐️CN DC | CN TG
‼️Please check the authenticity of all OKX links or channels at OKX channel verification
🏆 OKX Bounty Hunt New Season #1🏆
Engage, Refer & Win!
Prize:
- $400 USDT weekly allocation
🥇 $100 | 🥈 $50 | 🥉 $30
4th to 6th - $20
7th to 10th - $15
11th - 20th - $10
How to earn points:
✅ Check In Daily -> GM OKX Fam #OKXBountyHuntNewSeason#1 every day 👉50000
✅ Chat & Engage - Chat actively (50+ characters) 👉20
✅ Invite Friends - 🔗 Tag Admins to get your personal invite link and invite more people to join OKX Announcement👉50
✅ Inviters earns extra 👉 10 per message sent by the invitee
✅ Share your reactions/emojis under the announcement posts
Check points🏆
Bounty Points
Bounty Ranking
More points!
👉 Share pictures and topics of New Year and crypto with the #hashtag in the chat
Join the event now👇👇👇
OKX Bounty Hunt New Season #1 Form
Our Socials:
⚜️Sign Up on OKX | Join Affiliate | TG | DC | Wallet TG | Wallet Announcement | OKX on Spotify | Twitter/X | YouTube
⭐️CN DC | CN TG
‼️Please check the authenticity of all OKX links or channels at OKX channel verification
Chat-Specific Hashtags. Groups and channels can use the new format#hashtag@username for hashtags – which only show posts and stories from the same chat when tapped.
October Features
1 • 2 • 3 • 4 • 5 • 6 • 7 • 8 • 9 • More