Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
➡️New build available for Xiaomi Redmi 9 Prime / Poco M2 (lava)
👤 by Sakthivel Nadar
ℹ️ Version: 13
📆 Build date: November 14, 2022 05:22
📂 File size: 1.62 GB
⬇️ Download now
#lava#pixelexperience
🪐 The exoplanet 55 Cancri e, orbiting a star about 41 light-years away in the constellation Cancer, is known for its fiery dayside, reaching temperatures above 2,400°C—hot enough to melt metal. This rocky world is likely covered by a massive ocean of molten lava, and some scientists think its carbon-rich composition could even mean parts of the planet’s interior are made of diamond. ✨
#exoplanets⚡#extremes⚡#lava⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Far from Earth, the exoplanet COROT-7b endures some of the most extreme conditions known: it orbits its star so closely that its surface reaches about 2,000°C, hot enough to melt rock. Scientists believe this heat turns the planet’s rocky crust into a vast, bubbling “lava ocean,” creating a world where rock vaporizes into the atmosphere and rains down as pebbles. ✨
#exoplanet⚡#extremes⚡#lava⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
Lava in Spain's La Palma engulfs more houses
Lava engulfed more buildings on the Spanish island of La Palma, destroying everything in its path about three weeks after the volcano began to erupt
#News#Reuters#LaPalma#Spain#Lava
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Spain's volcano is still erupting, no end in sight
There's no end in sight to the volcanic eruption that has caused chaos and destruction on the Canary island of La Palma since it began about a month ago
#News#Reuters#LaPalma#Spain#Lava#Volcano
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
LIVE: Building-sized lava blocks fall from volcano on Spain's island La Palma
Blocks of molten lava as large as three-story buildings rolled down a hillside on the Spanish island of La Palma on Sunday while a series of tremors shook the ground three weeks after the volcano erupted.
#News#Reuters#Live#volcano#lava#LaPalma#Spain
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
LIVE: Lava spreads on Spain's La Palma with no end in sight to volcanic eruption
Flows of molten rock pour from the Cumbre Vieja volcano — in its fourth week of eruption — threatening to engulf another area on the Spanish island of La Palma.
#News#Reuters#Live#volcano#lava#LaPalma#Spain#environment
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
LIVE: Drone captures view of La Palma's Cumbre Vieja volcano
Drone footage shows the impact of the Cumbre Vieja volcano on La Palma, Spain.
#News#Reuters#Live#volcano#lava#LaPalma#Spain#environment
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Lava spews from La Palma volcano
The Cumbre Vieja volcano on Spain's La Palma island continues to spew lava and smoke.
#Volcano#LaPalma#Spain#Lava#CanaryIslands#CumbreVieja#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖