Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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 truth is that the European Union entered the #RussiaUkraineWar recklessly, based on flawed calculations and with a misguided strategy, and I attribute this to the actions of President @vonderleyen.
https://t.me/PM_ViktorOrban
Mood in Russia turns bleak as war in Ukraine drags on and economy suffers
[Read FullArticle]
@WorldNews#RussiaUkraineWar#RussianEconomy#GlobalNewsUpdate
'Serious disruption' — Russian oil pumping station in Nizhny Novgorod Oblast hit by Ukrainian drones, SBU source says
[Read FullArticle]
@WorldNews#RussiaUkraineWar#UkrainianDrones#OilInfrastructure
Russia suffers ‘record’ soldier casualties as Ukraine ups drone production | Russia-Ukraine war News
[Read FullArticle]
@WorldNews#RussiaUkraineWar#UkraineDroneStrike#WarNewsUpdate
❗️🇷🇺🇺🇦We will win by all means, but it's better to win sooner, so that fewer people from this side and that side die!
"Our president did everything he could to avoid war, but he was not heard and did not want to be heard," says a Russian soldier who was mobilized last September, one should always try to negotiate. And President Putin offered to sit down at the negotiating table, but instead the Ukrainians were seriously preparing for war! But we will definitely win, because we cannot retreat, we have to solve it here and now, otherwise they will come to us! Of course, we would like it to be quicker, so that fewer people would die on this side and on that side. Precisely peaceful people, not Nazis. Participating in this special operation is our man's duty, says the young warrior!
#RussiaUkraineWar
#frontNews
#RussiaVictory
https://t.me/heroesofZ/312
📱InfoDefenseENGLISH
📱InfoDefense
The Commonwealth of Independent States (CIS) was established on 8 December 1991 to succeed the Soviet Union, but Russia’s 2014 Crimea annexation and 2022 invasion have deeply shaken its unity and future. 🌐
[Read more]
@googlefactss
#CIS#Geopolitics#RussiaUkraineWar#History#InternationalRelations