Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🌍 Slovenia’s Škocjan Caves feature an underground canyon over 100 meters deep—the largest in Europe. This karst wonder drains rivers directly from the surface into vast hidden chambers. ✨
#caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In Croatia’s Dinaric Alps, karst landscapes hide more than 10,000 known caves and sinkholes. Some systems stretch for over 20 kilometers underground, hosting rare, blind aquatic animals. ✨
#caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The world’s largest cave chamber by volume, Sarawak Chamber in Borneo, is big enough to hold 40 jumbo jets. This massive cavern formed naturally in a karst limestone landscape. ✨
#caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Vietnam’s Phong Nha Cave features tunnels over 44 kilometers long, with underground rivers and rare cave pearls—smooth mineral balls formed by dripping water in the dark. ✨
#caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Some karst caves hold unique stone towers called "speleothems," which form slowly from dripping water. These underground forests can grow over tens of thousands of years. ✨
#caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Caves in karst landscapes can grow huge underground chambers thanks to rainwater slowly dissolving limestone rock. Some contain rare crystals and underground rivers hidden from the surface. ✨
#caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Rainwater can carve entire underground labyrinths in karst landscapes, creating vast networks of caves, tunnels, and sinkholes—some so deep and complex that new passages are still being found today. ✨
#caves⚡#karst⚡#erosion⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some of the world’s longest underground rivers are hidden in karst landscapes. These rivers can travel for dozens of kilometers beneath the surface before emerging in springs or caves. ✨
#caves⚡#karst⚡#hydrology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The world’s largest karst region is in southern China, where vast limestone hills, towers, and deep caves house rare species found nowhere else on Earth, including blind fish and giant salamanders. ✨
#karst⚡#caves⚡#limestone⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In Croatia’s Velebit Mountains, karst landscapes feature underground streams that vanish into deep sinkholes, only to reappear as powerful springs many kilometers away. ✨
#karst⚡#caves⚡#springs⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some karst caves contain rare bacteria that feed on mineral rock, creating colorful biofilms and even helping form new cave crystals—making the underground world alive in ways few people expect. ✨
#caves⚡#karst⚡#microbiology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels