Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🌍 The Madagascar and Indian Ocean Islands hotspot is home to over 11,000 plant species, and about 80% of them exist nowhere else—an extraordinary concentration of unique life. ✨
#biodiversity⚡#islands⚡#conservation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
👆तेंदुए की दहाड़ से गूंजता जंगल।। 🐾🐆
8% की वृद्धि के साथ, 2022 में तेंदुए की आबादी संख्या 13,874 पहुंची, जो कि 2018 में 12,852 थी।
#Conservation
#Wildlife
🌎 On the plains of Mongolia, the Przewalski’s horse gallops wild—the only truly wild horse species left on Earth. Unlike domestic horses, it has never been tamed, boasting a stocky build, upright mane, and a unique history of survival after near-extinction in the wild. ✨
#wildlife⚡#conservation⚡#mammals
👉subscribe Interesting Planet
🌍 Costa Rica’s biodiversity hotspot holds more plant species in just one hectare than most European countries have nationwide, showcasing how concentrated life can be in these rare regions. ✨
#biodiversity⚡#conservation⚡#tropics⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
Selamat Hari Raya Haji! ✨
In the first episode of our new series ‘Your POV’, see through the eyes – and lens – of photographer @izmyphotos📸
We’ll celebrate Hari Raya Haji while exploring Masjid Alkaff Upper Serangoon – a recipient of the Architectural Heritage Award (AHA) in 2015 for retaining the vision of the original architects 🕌
Curious about other AHA winners?
👉 Check it out here: go.gov.sg/AHA2024TG
#ExploreSingapore#Conservation#ArchitectureSG
🌍 The Sundaland region in Southeast Asia is a biodiversity hotspot where over 15,000 plant species are found, nearly half of which exist nowhere else on Earth. ✨
#biodiversity⚡#hotspots⚡#conservation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Eastern Arc Mountains in East Africa are a biodiversity hotspot where 75% of the area's plant species exist nowhere else on Earth—making it one of the planet’s most unique natural vaults. ✨
#biodiversity⚡#conservation⚡#ecology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 In the Gulf of California, the vaquita porpoise is the world’s rarest marine mammal, with fewer than 10 left. Its shy nature and distinctive dark eye rings make it unique, but illegal fishing nets threaten its survival. ✨
#vaquita⚡#conservation⚡#ocean
👉subscribe Interesting Planet
🌎 The Svalbard Global Seed Vault, buried deep in a Norwegian mountain, stores over a million seed varieties as a backup for global agriculture—safeguarding food diversity for future generations. ✨
#biodiversity⚡#conservation⚡#vault
👉subscribe Interesting Planet
🌎 The black robin of New Zealand bounced back from just five birds left in the world in 1980—thanks to devoted conservation, their population is now stable. This comeback highlights how careful human intervention can save even the rarest species from extinction. ✨
#conservation⚡#wildlife⚡#recovery
👉subscribe Interesting Planet
🌎 The Okavango Delta in Botswana transforms each year from dry savanna to a maze of wetlands due to annual flooding, but modern irrigation and water extraction upstream have reduced natural flows. This human impact threatens a UNESCO World Heritage site that supports over 400 bird species and large populations of elephants and hippos. ✨
#conservation⚡#wetlands⚡#Africa
👉subscribe Interesting Planet
👉more Channels
🌍 Nearly 10 million hectares of forest are lost each year, but new satellite tracking helps spot illegal logging and monitor regrowth, making large-scale forest recovery more achievable than ever. ✨
#deforestation⚡#satellites⚡#conservation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍