Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
News: Over 529,000 refugees return to #Sudan in two years, UN says
More than 529,000 refugees have returned to Sudan from neighbouring countries over the past two years, according to the International Organization for Migration (#IOM).
In a report released on Sunday, the agency said it had registered 529,661 people who crossed back into Sudan between January 2024 and December 2025.
Sudan has been gripped by conflict since April 2023, when fighting erupted between the Sudanese army and the Rapid Support Forces (RSF) over the integration of the paramilitary group into the armed forces. The war has triggered what the United Nations describes as one of the world’s worst humanitarian crises, with tens of thousands reported killed and around 13 million people displaced.
Approximately 4.5 million people fled to neighbouring countries during the conflict and are considered refugees, according to recent UN ....
https://www.middleeastmonitor.com/20260216-over-529000-refugees-return-to-sudan-in-two-years-un-says/
News: One-Third of #Sudan’s population displaced in 1,000 days of conflict, #IOM says
Nearly one in three people in Sudan has been displaced internally or across borders over the past 1,000 days of conflict, marking the largest displacement crisis in the world, according to the International Organization for Migration (IOM).
In a statement, IOM said an average of five displacement-triggering events occurred each week since fighting erupted on 15 April 2023, devastating communities and uprooting millions.
The organization reported that 743 incidents have triggered displacement, including 524 conflict-related events and 219 natural hazards such as floods and fires.
IOM data show that more than 15 million people have been forced from their homes, with 11.58 million displaced inside Sudan and around four million fleeing across borders at the peak of the crisis.
The conflict has ...
https://web.facebook.com/AddisstandardEng/posts/pfbid024AJ4oLUYMTu3M13vCpNyUwTBCKqwaRquc8JCJcxXiGr7to3Zh4ChVSp32zrDRW2el
27–28 октября 2022 г., Алматы, Казахстан
Данное мероприятие проводится в рамках регионального проекта Международной организации по миграции «Защита уязвимых мигрантов с особым акцентом на расширение прав и возможностей женщин в контексте миграции в Центральной Азии»
#iom#nihol#узбекистан#ташкент
Визит делегации Узбекистана в Казахстан
Проведение обучения на местах и анализа выполнения межправительственных соглашений в области трудовой миграции.
#iom#nihol#узбекистан#ташкент
News: #Ethiopia migration surges 18% in 2025 as economic hardship, smuggling shifts drive flows; Eastern Route turns deadliest on record
Outgoing #migration from Ethiopia along the #Eastern Route rose sharply in 2025, with total tracked movements increasing by 18% to more than half a million, underscoring growing economic pressures and evolving smuggling dynamics, the International Organization for Migration (#IOM) said.
Read more: https://addisstandard.com/?p=56046
Международный форум на тему " Новые тенденции миграции в условиях пандемий, управление миграцией и защита мигрантов"
https://fb.watch/2vUtaB3Pm_/
#мыпротивнасилия#насилие#стопнасилию#iom#nihol#узбекистан#ташкент
News: Nine dead, dozens missing in #Djibouti shipwreck as #Ethiopian migrants dominate risky route
Nine migrants have died and 45 others remain missing after a boat sank off the coast of Djibouti this week, according to the International Organization for Migration(#IOM), in the latest tragedy along a route heavily used by Ethiopian migrants, AFP reported.
The #UN migration agency said the incident occurred overnight on 24 March near the northern town of #Obock, with 320 people believed to have been on board at the time of the shipwreck. Rescue efforts are ongoing as dozens remain unaccounted for.
The disaster underscores the continued risks faced by Ethiopian migrants, who make up the majority of those traveling along the Eastern Route, a perilous journey from the Horn of Africa across the Red Sea toward #Yemen and onward to #Gulf_states in search of work.
Read more: https://addisstandard.com/?p=56116
Мулоқоти вазир бо роҳбари Дафтари минтақавии Созмони байналмилалии муҳоҷират (IOM) барои Аврупо ва Осиёи Марказӣ
5 августи соли 2025 вазири корҳои хориҷии Ҷумҳурии Тоҷикистон Сироҷиддин Муҳриддин бо роҳбари Дафтари минтақавии Созмони байналмилалии муҳоҷират барои Аврупо ва Осиёи Марказӣ Артур Эркен дар ҳошияи Конфронси сеюми Созмони Милали Муттаҳид оид ба Гурӯҳи кишварҳои рӯ ба тараққии маҳсур ба хушкӣ дар шаҳри Авазаи Туркманистон мулоқот анҷом дод.
#Тоҷикистон#Муҳоҷират#Ҳамкорӣ#СММ#Аваза2025
Встреча Министра с Региональным Директором Офиса Международной организации по миграции (IOM) для Европы и Центральной Азии
5 августа 2025 года Министр иностранных дел Республики Таджикистан Сироджиддин Мухриддин встретился с Главой регионального Офиса Международной организации по миграции (IOM) Артуром Эркеном на полях Третьей Конференции ООН по развивающимся странам, не имеющим выхода к морю, в городе Аваза, Туркменистан.
#Таджикистан#Миграция#Сотрудничество#ООН#Аваза2025
Meeting of the Minister with the Regional Director of IOM Office for Europe and Central Asia
On August 5, 2025, Sirojiddin Muhriddin, Minister of Foreign Affairs of the Republic of Tajikistan, met with Arthur Erken, Regional Director of the IOM Office for Europe and Central Asia, on the margins of the Third United Nations Conference on Landlocked Developing Countries (LLDC3) in the city of Avaza, Turkmenistan.
#Tajikistan#IOM#Cooperation#UN#Avaza2025
@mfa_tj