Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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 deepest point on land is the Bentley Subglacial Trench in Antarctica, buried beneath almost 3 kilometers of ice. This hidden valley lies 2,555 meters below sea level, far deeper than Death Valley, and remains inaccessible except through advanced radar technology. ✨
#Antarctica⚡#geology⚡#extremes
👉subscribe Interesting Planet
🌍 The Gobi Desert experiences freezing winters with temperatures dropping below –40°C, making it one of the few deserts known for both scorching heat and extreme cold. ✨
#deserts⚡#climate⚡#extremes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 High-altitude deserts like the Atacama in Chile are among Earth’s driest extreme climate zones, receiving less than 2 millimeters of rain a year. These parched regions are so arid that some weather stations have never recorded rainfall. ✨
#climate⚡#desert⚡#extremes
👉subscribe Interesting Planet
🌍 Antarctica’s interior is the only place on Earth with a true polar climate—temperatures rarely rise above freezing, and less precipitation falls each year than in most deserts. ✨
#climatezones⚡#antarctica⚡#extremes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Earth holds the record for the highest known surface temperatures for a rocky planet in our Solar System, with some desert spots topping 56°C—hotter than the ground on Venus or Mars. ✨
#planet⚡#deserts⚡#extremes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 Rising in the Peruvian Andes at 5,100 meters, La Rinconada is the world’s highest permanent settlement. Over 40,000 people live here, mostly mining gold in challenging conditions with no running water or sewage system. ✨
#settlements⚡#geography⚡#extremes
👉subscribe Interesting Planet
👉more Channels
🌎 Life thrives in Earth’s extreme climate zones, like the frigid polar regions and the hyper-arid Atacama Desert. The Atacama receives less than 2 mm of rain annually, making it one of the driest places on Earth, while Antarctica sees winter temperatures plunge below –60°C. ✨
#climate⚡#extremes⚡#geography⚡#adaptation
👉subscribe Interesting Planet
👉more Channels
🌍 The Lut Desert in Iran holds the record for Earth’s hottest land temperature ever measured from space—an astonishing 80.8°C, far exceeding typical desert heat. ✨
#deserts⚡#temperature⚡#extremes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🪐 In 2016, astronomers using the Hubble Space Telescope observed the exoplanet WASP-121b, where temperatures in its stratosphere soar above 2,500°C and molecules such as water vapor exist as glowing, superheated gas. The planet’s intense gravity causes it to stretch into a teardrop shape, while metals like iron and magnesium escape its atmosphere, streaming into space in a shimmering trail. ✨
#exoplanets⚡#atmosphere⚡#extremes
👉subscribe Universe Mysteries
🌎 The coldest permanently inhabited place is Oymyakon, Russia, where winter temperatures drop below −50°C. The hottest surface temperature recorded was 80.8°C in Iran’s Lut Desert in 2005. ✨
#climate⚡#extremes⚡#Earth⚡#geography
👉subscribe Interesting Planet
🌎 Nestled in the Siberian taiga, the Russian town of Verkhoyansk is one of the coldest inhabited places on Earth. Winter temperatures can drop below –50°C, and the town recorded a range of over 105°C between its lowest and highest temperatures—a world record for temperature variation in a single settlement. ✨
#cities⚡#Siberia⚡#extremes
👉subscribe Interesting Planet
👉more Channels
🪐 Exoplanet 2MASS J2126–8140 holds the record for the widest known orbit around its star—about 1 trillion kilometers away, or nearly 7,000 times the distance from Earth to the Sun. This gas giant drifts so far from its host that a single "year" there lasts nearly 900,000 Earth years, exposing it to the coldest, loneliest planetary conditions ever measured. ✨
#exoplanets⚡#extremes⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels