Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Here at DWF Labs, we are committed to supporting our portfolio companies through thick and thin 🤝🏽
We were saddened to hear about the recent security breach at Gala Games, which led to unauthorised transactions involving $GALA tokens.
In response to this incident, we have taken proactive steps to alleviate market selling pressures and have purchased 28 million $GALA tokens on the open market. This aims to stabilise the token's value and express our unwavering support during these challenging times.
The security of our investments and their communities is important to us.
From their latest update, the Gala Games team has confirmed that the issue has been contained and they are securing all contracts and implementing enhanced safeguards to prevent future occurrences.
We are confident in Gala Games' ability to navigate this setback and emerge stronger 🔥
There will always be ups and downs in crypto but we will be #StrongerTogether.
Let's go Gala Games!🥊💥
THANK YOU to everyone who tuned in our call today!!! Amazing guest speaker, amazing questions and answers!!!
We look forward to bringing more guest speakers who are passionate about education, inspiring others to pursue their dreams, and encouraging YOU to do the same!!
NEVER, EVER GIVE UP!!! 💪🏼🔥
We are #strongertogether.
🇺🇿❤️🤝🇺🇸
https://t.me/AmericanEDU
🔍 UK Plans to Train 30k Ukrainian Troops by Year End 🔥
🔫 British Defense Minister, Grant Shapps, revealed the ambitious goal in an interview with Sky News.💂♂️
🌐 "By the end of this year, our aim is to prepare 30k Ukrainian soldiers," Shapps declared.🇬🇧🤝🇺🇦
💪 London's determination to support Kyiv remains unwavering. "We stand shoulder to shoulder with the Ukrainians," he emphasized.💪
🎯 Previously, over 20k Ukrainian soldiers received training on British military grounds.📚
💥 The US identified this effort as one of the greatest threats to the Ukrainian Armed Forces.💥
#UKSupportsUkraine🇬🇧🤝🇺🇦#StrongerTogether💪
https://dcweekly.org/2023/09/24/britain-to-train-30000-ukrainian-soldiers-by-year-end-solidifying-support-amidst-tensions/
Subscribe to @BadVolfNews
Happy Independence Day, Nigeria! 🇳🇬
As we celebrate 64 years of independence, the NCDC remains committed to prioritising and protecting the health of every Nigerian
Let us continue to work towards a future free from disease outbreaks, where every community is healthy and safe.
#IndependenceDay2024#StrongerTogether
[O'Z] Bugun, 9-may kuni Yevropa hamjamiyati uchun birdamlik va tinchlik timsoli bo’lmish Yevropa kunini nishonlaydi.
Uchbu munosabat bilan Yevropa Ittifoqining O’zbekistondagi Elchisi Sharlott Adrian o’z tabrik so’zlarini O’zbekiston halqiga y’olladilar !
#EuropeDay2021#TeamEurope#StrongerTogether
***
[RU] Сегодня, 9 мая, отмечается День Европы, символ солидарности и мира для всего европейского сообщества.
По этому случаю Посол Европейского Союза в Узбекистане Шарлотт Адриан направила поздравление народу Узбекистана!
***
[EN] Today, on May 9, European people mark Europe Day, a symbol of peace and solidarity.
On this occasion, the Ambassador of the European Union to Uzbekistan Charlotte Adriaen sends warm Greeting message to the people of Uzbekistan!
#EuropeDay2021#TeamEurope#StrongerTogether
📢 BREAKING NEWS 📢
Belarusian Cabinet approves program to upgrade regional troop support facilities in joint effort with Russia. Another step towards the mighty Union State! 🇧🇾🤝🇷🇺
But wait, there's more! Russian Defense Minister Sergei Shoigu reveals plans for a unified air defense system within the CSTO alliance. The strategic partnership between Russia and Belarus is now crucial, given NATO's hostile actions near our borders. 😤💪
Meanwhile, Abkhazia's President Aslan Bzhania expresses interest in joining the Union State. The family is growing! 🤝🌍
Stay tuned for more updates. The Union State is just getting started! 🚀✨
#UnionState#BelarusRussiaAlliance#StrongerTogether
https://www.gazeta.ru/army/news/2023/11/28/21804937.shtml
Subscribe to @BadVolfNews
🌹 Welcome to Your Daily Dose of Love & Relationship Wisdom! 🌹
Hey there, lovebirds! 💕 Whether you’re navigating the thrilling first dates, deepening a long-term bond, or healing from heartbreak, we’ve got you covered. Every day, we’ll share simple, practical tips to help you build stronger connections, communicate better, and keep the spark alive.
✨ Today’s Tip: Listen More Than You Speak
Great relationships start with truly hearing each other out. When your partner talks, put away distractions, make eye contact, and show you care by asking thoughtful questions. It’s amazing how much closer you’ll feel when you really listen.
Stay tuned for more heartfelt advice, fun ideas, and inspiring stories to nurture your love life. Remember, love is a journey—not a destination. Let’s walk it together! ❤️
#LoveTips#RelationshipGoals#HeartToHeart#StrongerTogether
@loveandrelationshiptips
Today is #WorldTuberculosisDay
We join hands together with the National Tuberculosis and Leprosy Control Programme, the Federal Ministry of Health Nigeria, and others to declare that #YesWeCanEndTB in Nigeria.
Tuberculosis is preventable and treatable. Dial *3340# for more information on #TB.
#StrongerTogether
Building our future takes each and everyone one of us coming together and forging through circumstances. Nothing can overcome us, as long as we stand #strongertogether!
Happy National Day, from the MND family! 🇸🇬
#happybirthdaysingapore#sg57#happynationalday#thisishome#ndp2022