Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Rovinj, #Croatia🇭🇷
Rovinj interestingly combines rich traditions and modernity, provincial charm and resort status. This city is still a fishing port, so seafood here is the freshest and tastiest.
Sibenik, #Croatia
Sibenik is the only Croatian city and certainly one of several in the world that boasts of having two UNESCO monuments: St. James Cathedral and the fortress.
🇭🇷#Croatia: Croatia has reintroduced compulsory military service after nearly 20 years.
Hundreds of young Croatians have reported for duty, with the first 800 conscripts beginning their two-month basic training at three barracks across the country: Knin, Slunj, and Požega.
Under the new system, up to 4,000 young men will be called up each year for short-term training. Croatian General Kundid said the program will be “very dynamic and very interesting” for conscripts.
Training will include traditional military skills as well as modern capabilities such as basic drone operation, drone defence, and cyberwarfare techniques and countermeasures.
(via @balkanspectator & BBC)
🗺 CROATIA 🇭🇷
A beautiful morning in the town of Rovinj🤩
The historic center of Rovinj is located on a peninsula shaped like a drop. The cathedral is located in the center.
Rovinj interestingly combines rich traditions and modernity, provincial charm, and resort status. This town is still a fishing port, so the seafood here is the freshest and tastiest.
#Croatia
@voyage
🗺 Croatia 🇭🇷
A beautiful morning in the town of Rovinj🤩
The historic center of Rovinj is located on a peninsula shaped like a drop. The cathedral is located in the center.
Rovinj interestingly combines rich traditions and modernity, provincial charm, and resort status. This town is still a fishing port, so the seafood here is the freshest and tastiest.
#Croatia
@voyage
Branko Mataja — Traditional And Folk Songs Of Yugoslavia (Essar Records, 1974)
#guitar#Serbia#Croatia#Yugoslavia
Свой единственный альбом с гитарными интерпретациями народной музыки Югославии Бранко Матая записал у себя дома. Все композиции он исполнил самостоятельно на модифицированной им самим же гитаре. Поэтому «Традиционные и народные песни Югославии» звучат скорее не как урок истории народной музыки родины Матаи, а как интимное, личное общение между исполнителем и слушателем.
Коллекция гитарных медитаций Бранко Матая оставалась в безвестности, пока не была вновь открыта в начале 2000-х. В 2022 году альбом перевыпустил лейбл Numero Group.
🔗Spotify | AppleMusic | Bandcamp
🇰🇬🇭🇷 В рамках официального визита Министра иностранных и европейских дел Республики ХорватияГордана Грлич Радмана в Кыргызскую Республику 12 декабря 2024 года состоялись его переговоры в узком и расширенном составе с Министром иностранных дел Кыргызской РеспубликиЖээнбеком Кулубаевым.
▶️Толук маалымат/Подробнее: mfa.gov.kg
#МИДКР#ТИМ#Kyrgyz_MFA#Kyrgyzstan#Croatia
Friendlies🏳
2026-03-31 23:00 UTC
USA vs. Portugal
Predicted outcome: USA❌
Predicted score: 3:2
Actual: Portugal 0:2
#USA#Portugal
2026-03-31 23:30 UTC
Argentina vs. Zambia
Predicted outcome: Argentina✅
Predicted score: 2:0
Actual: Argentina 5:0
#Argentina#Zambia
2026-04-01 00:00 UTC
Brazil vs. Croatia
Predicted outcome: Brazil✅
Predicted score: 2:1
Actual: Brazil 3:1
#Brazil#Croatia
2026-04-01 01:00 UTC
Mexico vs. Belgium
Predicted outcome: Belgium❌
Predicted score: 1:3
Actual: Draw 1:1
#Mexico#Belgium
#Football#Friendlies