Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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 BLEEDING HEARTS OF ETHIOPIA'S MOUNTAINS** ❤️🔥
*Africa's Most Mysterious Primates*
High in Ethiopia's Simien Mountains lives one of nature's most enigmatic creatures - the Gelada baboon. Known as "bleeding heart monkeys," these remarkable primates carry a crimson badge across their chest.
primates carry a c💔 Red chest patches that intensify with emotion
🏔️ Only primates adapted to extreme altitude living
🌿 90% grass diet - nature's lawnmowers
👥 Largest primate gatherings on Earth
Gelada baboon. Know💰 Exclusive encounters: $6,000-10,000 per trek
📸 Photography expeditions with premium rates
🎬 Untold documentary potential
Found nowhere else on Earth, geladas represent millions of years of evolution. Their "bleeding hearts" aren't wounds - they're windows into Africa's most extraordinary survival story.
#GeladaBaboon#EthiopiaWildlife#SimienMountains
🦁 SIMIEN MOUNTAINS: WHERE LIONS WALK IN CLOUDS 🏔️
*Ethiopia's Kingdom Above the Clouds at 4,000+ Meters*
In the remote highlands of northern Ethiopia lies one of Africa's most spectacular wilderness areas - the Simien Mountains, where majestic lions roam at altitudes higher than most European peaks.
The Last High-Altitude Lions:
🌟 Altitude record: 4,620m - highest lion habitat on Earth
⚡ Population: Only 50-80 lions remain in this unique ecosystem
🏔️ Terrain: Dramatic escarpments, deep gorges, alpine meadows
Tourism Gold Rush:
• Exclusive experience: 99% of tourists never see high-altitude lions
• Photography paradise: Lions silhouetted against cloud-covered peaks
• Adventure tourism: $3,000-5,000 per expedition
The Simien Mountains offer what no other destination can - lions literally walking among clouds in Earth's most dramatic landscape.
#SimienMountains#EthiopianLions#AdventureTourism#WildlifePhotography
🦁 **SIMIEN MOUNTAINS: WHERE LIONS WALK IN CLOUDS** 🏔️
*Ethiopia's Kingdom Above the Clouds at 4,000+ Meters*
In the remote highlands of northern Ethiopia lies one of Africa's most spectacular wilderness areas - the Simien Mountains, where majestic lions roam at altitudes higher than most European peaks.
**The Last High-Altitude Lions:**
🌟 **Altitude record**: 4,620m - highest lion habitat on Earth
⚡ **Population**: Only 50-80 lions remain in this unique ecosystem
🏔️ **Terrain**: Dramatic escarpments, deep gorges, alpine meadows
**Tourism Gold Rush:**
• **Exclusive experience**: 99% of tourists never see high-altitude lions
• **Photography paradise**: Lions silhouetted against cloud-covered peaks
• **Adventure tourism**: $3,000-5,000 per expedition
The Simien Mountains offer what no other destination can - lions literally walking among clouds in Earth's most dramatic landscape.
#SimienMountains#EthiopianLions#AdventureTourism#WildlifePhotography
🐺 **THE LAST GUARDIANS OF ETHIOPIA'S HIGHLANDS** 🏔️
*Africa's Rarest Predator on the Edge of Extinction*
High in Ethiopia's Simien Mountains, where mist meets sky at 4,500 meters, lives the world's rarest wolf. Only 500 Ethiopian wolves remain - each one a living treasure of ancient Africa.
**The Numbers Tell the Story:**
⚡ **Population**: Less than 500 individuals left on Earth
🏔️ **Habitat**: Highest-altitude wolves in the world
🎯 **Hunting**: 90% success rate targeting giant mole-rats
💰 **Tourism value**: $8,000-12,000 per wildlife expedition
**Why This Matters:**
Every Ethiopian wolf represents millions of years of evolution. These apex predators maintain the delicate balance of highland ecosystems while creating premium eco-tourism opportunities worth millions to local communities.
*In Ethiopia's misty peaks, every wolf howl echoes the heartbeat of Africa's wild soul.*
#EthiopianWolf#EndangeredSpecies#SimienMountains#WildlifeConservation#EthiopiaWildlife
## ⛰️ THE ROOF OF AFRICA: WHERE EARTH TOUCHES HEAVEN
## ⛰️ የአፈሪካ ጋራ: ምድር ሰማይ የሚመሰከርበት
🌍 КОГДА ГОРЫ КАСАЮТСЯ НЕБЕС!
Simien Mountains — Ethiopia's crown jewel and UNESCO World Heritage site where ancient volcanic peaks pierce the clouds at 4,500 meters! ⛰️
🌅 THE DRAMATIC LANDSCAPE:
These jagged ridges were sculpted by millions of years of volcanic fury, creating one of Earth's most breathtaking panoramas.
*Эти зубчатые вершины — самый драматичный пейзаж на планете!*
*እነዚህ የተበዳደሩ አጫያዎች በዓለም ውስጥ የተሳከሩ ምብጣት ምክንያቶች ነው!*
Deep gorges plunge 1,500 meters below — called "the chess pieces of the gods" by locals for their dramatic, sharp pinnacles.
🐒 UNIQUE WILDLIFE:
Home to the endangered Gelada baboons — the "bleeding heart" monkeys found NOWHERE else on Earth!
*Самые редкие павианы в мире живут только здесь!*
*በዓለም አንደ ቦታ የሚገኙ የጋላዳ ብድንዎች እዚህ ብቻ ይገኛሉ!*
These gentle giants graze the highland meadows in massive troops, living peacefully at altitudes that would leave most humans breathless.
🌟 KUINDZHI'S VISION BROUGHT TO LIFE:
At sunset, these mountains transform into layers of gold and shadow — like stepping into a painting by the Russian master Arkhip Kuindzhi. Light becomes sculpture, air becomes canvas, and the soul expands infinitely.
*На закате горы превращаются в живую картину Куинджи!*
*በሰሙን መግረብ ጋታ አያቶች የኩይንዅጂ እሳት ይሆናሉ!*
This is Ethiopia. Where nature paints with light and shadows, where time stands still, and where every breath feels sacred.
📸Swipe through:
Photo 1-2: Real dramatic vistas → Photo 3: Algorithmic art in Kuindzhi style!
*Фото 1-2: Реальные панорамы → Фото 3: Алгоритмическое искусство!*
#SimienMountains#የሲሚኤንአያቶች#Ethiopia#ኢትዮጵያ#UNESCO#Kuindzhi#AlgorithmicArt#የአልገሪዝምእሳት#EthiopianHighlands#የኢትዮጵያአያቶች#MountainMagic
🇪🇹@ethiopia