Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
#Explosion reported in #Mekelle; Officials say no casualties
An explosion occurred late Thursday in Mekelle near the Social Science campus of Mekelle University, though officials say there were no casualties or property damage.
Redahegn Feseha, head of the Mekelle Peace and Security Bureau, told local radio that the blast happened at around 9:30 p.m. near the upper gate of the city’s business campus. He described the incident as a deliberate act aimed at creating fear rather than causing harm, urging residents to remain calm and to condemn what he called an “act of terror.”
Residents reported a mix of fear and confusion. “I was sitting with my family when we heard a loud bang. My kid and my wife were terrified,” said one resident. Another added, “At first, we thought it was a drone attack or something falling. But later we heard it was a bomb.”
https://www.facebook.com/share/p/19x2dWByCq/
🇨🇳Le bilan de l’explosion dans une usine de feux d’artifice en Chine s’est alourdi à 21 morts et 61 blessés, a rapporté la Télévision centrale de Chine.
#chine#explosion
🇨🇳 Une explosion s’est produite dans une usine de feux d’artifice en Chine, faisant 3 morts et 25 blessés, a rapporté l’agence Xinhua.
Vidéo: My Fair Lady/X
#chine#usine#explosion
🇮🇷🇮🇱🇺🇸 Plusieurs civils ont été tués dans l’explosion de mines dissimulées dans des boîtes de conserve, larguées par des avions américains et israéliens près de la ville de Chiraz, dans le sud de l’Iran, rapporte l’agence Tasnim.
#iran#explosion#bilan
🇺🇸Cinq personnes ont été blessées à la suite d’une explosion de gaz dans une église de Boonville (État de New York), a rapporté la chaîne CBS News.
#étatsunis#église#explosion
🇨🇳 Une explosion s’est produite dans une usine de feux d’artifice en Chine, faisant 3 morts et 25 blessés, a rapporté l’agence Xinhua.
Vidéo: My Fair Lady/X
#chine#usine#explosion
🇬🇧 En Irlande du Nord, un homme a été arrêté après l'explosion d'une voiture devant un commissariat de police. Des perquisitions sont en cours à plusieurs adresses de Belfast, indique un communiqué de la police régionale.
#royaumeuni#voiture#explosion
🇦🇪Une explosion a eu lieu dans un immeuble du centre financier international de Dubaï, aux Émirats arabes unis, a rapporté le commentateur politique Mario Nawfal sur le réseau social X.
#émirats#explosion#immeuble
🇬🇧 Un obus non explosé de la Seconde Guerre mondiale a été neutralisé par une explosion contrôlée dans la ville de Plymouth, dans le sud-ouest de l'Angleterre. La BBC a diffusé une vidéo de l'explosion.
La bombe aérienne allemande SC250, une bombe à explosion pesant environ un quart de tonne, a été découverte le 30 avril par un propriétaire qui creusait une tranchée sur son terrain dans le quartier de Southway. La zone a été bouclée et les habitants de près de 1.200 maisons avoisinantes ont dû évacuer leurs domiciles.
#royaumeuni#explosion#obus
🇧🇮 Des dizaines de personnes ont péri dans l’incendie provoqué par des explosions survenues dans un dépôt de munitions à Bujumbura, la capitale économique du Burundi, a rapporté l’Agence France-Presse (AFP).
#burundi#explosion#incendie#victimes