Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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 invention of the safety elevator by Elisha Otis in 1852 made skyscrapers possible. His design featured a locking mechanism that stopped the elevator if the hoisting cable snapped. Otis demonstrated this life-saving device at the 1854 World’s Fair in New York, boosting public trust in elevators. ✨
#inventions⚡#history⚡#engineering
👉subscribe Interesting Planet
👉more Channels
🌎 X-rays were discovered accidentally in 1895 by German physicist Wilhelm Röntgen. While experimenting with cathode rays, he noticed an unknown radiation that could pass through solids and reveal images of bones. Today, X-rays are a key tool in medicine and industry worldwide. ✨
#inventions⚡#history⚡#physics
👉subscribe Interesting Planet
👉more Channels
🌎 The invention of the modern stethoscope in 1816 by French physician René Laennec transformed medical diagnosis. By rolling paper into a tube, Laennec could hear internal chest sounds clearly, improving detection of lung and heart conditions. The first stethoscopes were made of wood and about 25 centimeters long. ✨
#history⚡#medicine⚡#inventions
👉subscribe Interesting Planet
👉more Channels
🌎 In 1867, Swedish chemist Alfred Nobel invented dynamite by stabilizing volatile nitroglycerin with an absorbent clay called kieselguhr. This made blasting much safer for construction and mining. Nobel later used his dynamite fortune to establish the Nobel Prizes in 1895. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 In 1903, the Wright brothers achieved the first powered, controlled, and sustained flight of an airplane at Kitty Hawk, North Carolina. Their aircraft, the Wright Flyer, flew for 12 seconds and covered 36 meters. ✨
#inventions⚡#aviation⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The accidental invention of safety glass happened in 1903, when French chemist Édouard Bénédictus dropped a glass flask coated with plastic cellulose nitrate. Rather than shattering, the glass cracked but held together, inspiring shatter-resistant windshields. By 1927, safety glass became standard in automobile manufacturing. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
The first vending machine was invented in the 1st century AD by Greek engineer Heron of Alexandria. It dispensed holy water when a coin was inserted—the weight tilted a lever, opening a valve to release water before the coin dropped. 💧⚖️
[Learn more]
@googlefactss
#History#Inventions#Engineering#AncientGreece
Professor Muhammed Uvaze ixtirolari Buyuk Britaniyada patentlashtirilgani haqida Hudud informatsion dasturida lavha tayyorlandi.
#hudud#patent#inventions
⬇️Biz ijtimoiy tarmoqlarda:
Veb-sayt | Telegram | Instagram | Facebook
🌎 The discovery of radioactivity in 1896 by Henri Becquerel revealed that uranium salts emit invisible energy. This led to the identification of new elements like polonium and radium by Marie and Pierre Curie. Their work contributed to the development of X-ray machines and atomic science. The Curies isolated just 1 gram of radium from 8 tons of ore. ✨
#radioactivity⚡#discovery⚡#inventions
👉subscribe Interesting Planet
🌀💦 South African Invention That Changed Pool Life
Did you know the automatic pool cleaner was invented in 🇿🇦 South Africa?
👨🔧 In 1974, hydraulics engineer Ferdinand Chauvier (pictured), who had moved from the Belgian Congo to South Africa, came up with a way to take the hassle out of pool cleaning.
The result? The legendary Kreepy Krauly — one of the very first automatic pool cleaners, designed and built in Springs, South Africa. 🌍✨
His invention made pools around the world easier to maintain — and became a proudly South African contribution to everyday comfort.
🏊♂️ From Johannesburg to Los Angeles, millions of pools have been cleaned thanks to Chauvier’s idea.
#Inventions#SouthAfrica#Innovation#KreepyKrauly#History#MadeInSA