Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Big news for Apple users! 🍏✨ Did you hear? Apple has finally allowed emulators on iOS, and Delta stands out as one of the best out there! 🎮 Have you given it a try yet? Share your thoughts below! #iOS#Emulators#Delta
🌍 The Mississippi River Delta’s vast freshwater wetlands act as a natural filter, removing pollutants and buffering storm surges. These shifting marshes shelter over 400 species of fish and wildlife. ✨
#wetlands⚡#delta⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Okavango Delta in southern Africa floods seasonally with rainwater from distant highlands, creating vast, ever-shifting freshwater wetlands that support hundreds of rare animal species. ✨
#wetlands⚡#delta⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Danube Delta in Eastern Europe contains over 30 distinct types of freshwater wetlands, making it one of the most biodiverse delta systems in the world outside the tropics. ✨
#wetlands⚡#delta⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Ethiopia’s Lake Tana is the source of the Blue Nile and is surrounded by freshwater wetlands that support dozens of bird species found nowhere else, making it a hotspot for endemic wildlife. ✨
#wetlands⚡#delta⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 River deltas like Vietnam’s Mekong and the Mississippi in the US form complex freshwater wetlands, creating twisting channels and islands that shelter rare fish, birds, and vital crops. ✨
#wetlands⚡#delta⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Wetlands in the Siberian taiga freeze solid each winter, yet come alive in spring to host millions of migrating birds. These seasonal deltas become some of the world’s richest breeding grounds. ✨
#wetlands⚡#delta⚡#migration⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Okavango Delta in Botswana is one of the few major river deltas that forms entirely inland, creating a lush wetland oasis in the middle of the Kalahari Desert. ✨
#rivers⚡#wetlands⚡#delta⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Sudd in South Sudan is the largest freshwater wetland in the Nile basin. During flood season, its floating reeds can form islands that drift for kilometers across the swamp’s surface. ✨
#wetlands⚡#delta⚡#Africa⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Some freshwater wetlands and deltas trap so much carbon in their soil that, hectare for hectare, they store more than most forests—making them powerful natural climate regulators. ✨
#wetlands⚡#delta⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Florida Everglades, a vast freshwater wetland, is the only place on Earth where alligators and crocodiles coexist in the wild, thanks to its unique mix of habitats and water conditions. ✨
#wetlands⚡#delta⚡#wildlife⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍