Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🌎 In the Norwegian Arctic, the town of Longyearbyen bans dying at home, as bodies can't decompose in permafrost. Residents who are terminally ill must travel to the mainland. This small settlement is also the northernmost town with over 1,000 people. ✨
#arctic⚡#settlements⚡#permafrost
👉subscribe Interesting Planet
👉more Channels
🌎 The Siberian permafrost preserves ice age seeds for tens of thousands of years. Scientists have revived ancient plants, like Silene stenophylla, from seeds frozen over 30,000 years ago—proving some life can return after millennia in the deep freeze. ✨
#permafrost⚡#botany⚡#revival
👉subscribe Interesting Planet
🌎 Norilsk, Russia, is a city built above the Arctic Circle and is so remote that it’s closed to most foreigners. Founded in 1935 for nickel mining, it endures harsh winters with temperatures as low as −55°C. Norilsk is one of the largest cities in continuous permafrost and has no rail or road connection to the rest of Russia. ✨
#Norilsk⚡#Arctic⚡#permafrost
👉subscribe Interesting Planet
🌍 Some tundra soils contain buried ice wedges that can be thousands of years old. When permafrost thaws, these ancient ice wedges melt, creating strange sinkholes called "thermokarst." ✨
#permafrost⚡#tundra⚡#landscape⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In tundra landscapes, some mosses and lichens can survive temperatures below –50°C and continue to photosynthesize under snow, making them some of the Earth’s hardiest plants. ✨
#tundra⚡#permafrost⚡#adaptation⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the far north, frozen permafrost soils hide ancient bacteria and seeds that can survive for thousands of years—emerging only when the tundra thaws after centuries of deep freeze. ✨
#permafrost⚡#tundra⚡#arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the Siberian tundra, permafrost preserves massive underground "ice wedges" that crack open each winter and refill with meltwater every spring, leaving polygon patterns visible from above. ✨
#permafrost⚡#tundra⚡#arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some tundra ponds form when summer sun thaws just the surface of permafrost, creating seasonal lakes that vanish each year. These ponds support bursts of life in otherwise frozen landscapes. ✨
#tundra⚡#permafrost⚡#arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the Arctic tundra, some permafrost layers are over 1,500 meters thick—deeper than most skyscrapers are tall. This frozen ground stores ancient DNA from plants and animals tens of thousands of years old. ✨
#permafrost⚡#tundra⚡#arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In some Arctic tundra areas, ancient animal tracks remain frozen in permafrost for thousands of years. When the ground thaws, these footprints reappear, revealing hidden stories of past wildlife. ✨
#permafrost⚡#tundra⚡#Arctic⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 Every summer in Siberia, mysterious craters known as "Yamal holes" appear in the Arctic tundra. These giant pits, sometimes 20 meters wide, form when underground methane gas builds pressure and violently explodes through permafrost. Scientists have identified at least 17 such craters since 2014, linking them to warming temperatures and melting ice. ✨
#permafrost⚡#methane⚡#explosions
👉subscribe Interesting Planet
👉more Channels
🌍 In parts of Siberia, thawing permafrost can trigger sudden ground collapses called “thermokarst.” These sinks reshape the tundra and can swallow trees or create lakes almost overnight. ✨
#permafrost⚡#tundra⚡#landforms⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels