Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Herzi Halevi's resignation as Chief of Staff of the Israeli Army triggered a wave of resignations within the military leadership, following the failures of October 7, 2023, during Operation "Noah's Flood" and the subsequent war and its aftermath.
#HerziHalevi#IsraeliArmy#Gaza#Israel
Israeli activists led by the radical bloc demonstrated in front of the Ministry of Defense building in the heart of Tel Aviv. While their soldiers entered the building, they denounced the ongoing Israeli war of extermination on the Gaza Strip. The protesters told the soldiers coming into work that whether they are pulling the trigger, pressing buttons or making coffee at an office, as long as they are wearing the uniform and serving the Israeli state, they are an accomplice in the mass murder, the torture, the suffering, and destruction of the lives of over two million people in Gaza.
#Israel#TelAviv#IsraeliArmy#GazaGenocide#Palestine
Even after killing them, the Israeli occupation forces torture Palestinian martyrs by crushing their bones in the Eastern Neighborhood of Jenin in the West Bank.
#Palestine#WestBank#Jenin#Israel#IsraeliArmy
As part of the initial retaliation to the Israeli assassination of senior leader Sayyid Fuad Shokor, Hezbollah decided to strike two strategic targets inside the Israeli depth.
#Hezbollah#Lebanon#SouthLebanon#IsraeliArmy#Israel#TelAviv
Although known for operating deep in its enemy’s territory while focusing on attacking and destroying specific targets and gathering accurate intelligence, the Maglan commando unit of the Israeli Army was ambushed by Hezbollah in South Lebanon. The trap was part of the underway confrontations while Israel is attempting to set a foot on Lebanon’s soil.
#SouthLebanon#Lebanon#Israel#IsraeliArmy#Maglan
The Israeli Ministry of Defense's Rehabilitation Department reveals a surge in soldiers receiving treatment since the #war began, far exceeding the injury figures previously reported by the #IsraeliArmy. What have #Hamas and #Hezbollah done to #IsraeliSoldiers ?
#Hezbollah Chief Sayyed Hassan #Nasrallah refuted Israeli claims about a preemptive strike ahead of “Operation Al-Arbaeen” in the #Israeli depth. He also set a condition of resuming the retaliation, which has to do with the enemy’s admitting of losses inflicted in first phase.
#Lebanon#SouthLebanon#IsraeliArmy
Members of the Mista'arvim unit of the Israeli Army disguise like Palestinians to gather intelligence and execute other missions. Every group is dissolved once its work is found out.
#IsraeliArmy#Israel#Gaza#GazaGenocide#Palestine#Mistaarvim
Lebanese #Hezbollah military media releases video showing bases targeted in #Israel part of the First Phase of its response to the assassination of senior commander Fuad Shukr and killing of several civilians in #Beirut's southern suburbs on July 31.
#Lebanon#SouthLebanon#Nasrallah#Gaza#Palestine#IsraeliArmy
#Hezbollah Chief Sayyed Hassan #Nasrallah announced targets behind “Operation Al-Arbaeen” on August 25, 2024 in the #Israeli depth, and unveiled important details about the qualitative operation that struck the #Mossad HQ in #TelAviv suburb.
#Lebanon#SouthLebanon#IsraeliArmy
#Hezbollah Chief Sayyed Hassan #Nasrallah announced targets behind “Operation Al-Arbaeen” on August 25, 2024 in the #Israeli depth, and unveiled important details about the qualitative operation that struck the #Mossad HQ in #TelAviv suburb.
#Lebanon#SouthLebanon#IsraeliArmy