Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🌎 In ancient China, giant panda pelts were considered symbols of peace and friendship. Emperors gifted them to rival kingdoms as precious gestures, showing diplomacy in action through nature’s rarest bear. ✨
#history⚡#animals⚡#diplomacy
👉subscribe Interesting Planet
🚨🇺🇸TRUMP TELLS IRAN "CALL US" AS PUTIN HOSTS TEHRAN'S TOP DIPLOMAT
🔹 Iranian Foreign Minister Abbas Araghchi lands in St. Petersburg today for emergency talks with Putin 🇷🇺
🔹 Trump abruptly canceled US-Iran face-to-face meeting scheduled in Pakistan, blaming Tehran's "excessive demands" 📞❌
🔹 Nine-week conflict continues with mutual blockades choking energy markets — oil prices surge nationwide 💰⛽
🔹 Strait of Hormuz remains partially closed as Iran seeks Russian backing after US diplomacy collapsed 🚢🔒
"The ball is in their court — call us when you're ready to be serious," Trump signals 📱
This is getting messy fast 😬🔥
#USNews#Iran#diplomacy
@america
Faces of #Uzbekistan#Diplomacy
Ambassadors, permanent representatives and general consuls of Uzbekistan abroad with the First Deputy Chair of the Senate of the Parliament Sodyq Safaev and the Deputy Minister of Foreign Affairs Sherzod Asadov, after the seminar training organised by the Senate.
P.S. Could you find only two women?
@Diplomatika
🚨🇺🇸U.S. INTEL: IRAN REJECTS PEACE TALKS
🔹 Multiple intelligence agencies assess Tehran unwilling to negotiate seriously 🕵️♂️
🔹 Iran believes it's winning, doesn't trust Trump after previous attacks mid-negotiations 💪
🔹 Trump claims military will wrap up Iran campaign within 2-3 weeks ⏰
🔹 President threatens to bomb ALL Iranian power plants if no deal - potential war crime ⚡
🔹 Tehran foreign ministry denies asking for ceasefire despite Trump's progress claims 🗣️
Iran wants real peace talks, not temporary fixes according to Pakistani officials! This war is FAR from over 😤🔥
#USNews#Iran#Trump#diplomacy
@america
🌍 The Arctic Council brings together eight countries to manage Arctic resources and navigate disputes, making this region one of the world’s best examples of peaceful geopolitical cooperation. ✨
#geopolitics⚡#Arctic⚡#diplomacy⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
The Venezuelan government accepted Washington’s offer to restart dialogue only weeks ahead of presidential elections on July 28. President Maduro emphasizes any talks will have Venezuela's sovereignty as a starting point.
Full story: https://venezuelanalysis.com/news/venezuela-to-restart-direct-talks-with-us-maduro-announces/
#Venezuela#UnitedStates#Diplomacy
🚨🇨🇺🇺🇸CUBA CONFIRMS SECRET TALKS WITH TRUMP ADMINISTRATION
🔹 Cuban President Díaz-Canel publicly admits holding bilateral talks with US officials 🤝
🔹 Discussions aim for historic economic deal - biggest opening since 1961 revolution 💰
🔹 Cuba releases 51 prisoners as Vatican-brokered goodwill gesture ahead of negotiations 🕊️
🔹 Trump threatens "friendly takeover" if Cuba refuses to make deal with Washington 💪
🔹 Island faces fuel crisis with NO oil shipments for 3 months due to US blockade ⛽
🔹 Secretary Rubio reportedly in secret talks with Raul Castro's grandson Raulito 🤐
This could END 65 years of Cold War hostility - but at what price? 🔥🌎
#Cuba#diplomacy#Trump
@america
📰 NEWS | Venezuela Reclaims US Diplomatic Venues as Rodríguez Promotes ‘Faith Diplomacy’
Venezuela has officially retaken its diplomatic headquarters in Washington, DC, after the properties were under US State Department control since 2023. Officials re-hoisted the national flag and announced a rehabilitation process to restore full consular services for Venezuelan nationals.
The development follows renewed diplomatic ties between Caracas and Washington and a US sanctions waiver permitting operations of Venezuelan missions. Authorities say the facilities will address passport processing, legal documentation, and citizen assistance after years of restricted access.
Read the full report here 👉🏾https://venezuelanalysis.com/news/venezuela-reclaims-us-diplomatic-venues-as-rodriguez-promotes-faith-diplomacy/
#diplomacy#Religion#USVenezuelaRelations
politics
Somaliland and the Evolution of Diplomatic Engagement After 34 Years of Isolation. Read.
https://borkena.com/2026/01/01/somaliland-and-the-evolution-of-diplomatic-engagement-after-34-years-of-isolation/#SomalilandRecognition#Somaliland#Diplomacy