Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🇮🇷 Breaking: University protests flare up across Iran
New student protests erupted at major Iranian universities as the new term began, with demonstrators honouring victims of last month’s deadly crackdown. Clashes were reported in Tehran, with chants targeting Supreme Leader Ali Khamenei and reviving the “Woman, Life, Freedom” movement.
The unrest comes amid rising geopolitical tensions, as the U.S. boosts its regional military presence while nuclear talks with Tehran remain unresolved. #News#Iran#University
「💻」#university#studying_tips
new semester, better me 📚🦪.
Yesterday I did a lot of stuff including unpacking and setting up my room for the semester.
Of course I will redecorate it, however I shouldn’t forget that this room is for only one semester
✨
Inshallah will go to study away
😻
~🐈~
↬@jastm1🌊
「💻」#university#studying_tips
❤️Some college x School inspo
✨A new chapter is here!✨
Are you ready for school/college? ✨
This is the perfect time to set new ambitions and new goals. A chance to start fresh, grow, and chase the best version of yourself. 🌱
Don’t be shy, step forward with confidence, give it your best, and make this year unforgettable.💗🫶
~🐈~
↬@jastm1🌊
「💻」#university#studying_tips
Checklist of things to pack for UNIVERSITY🥳!
Most of you might be overwhelmed with the amount of things to do, but don't worry you've got this 💪.
Save not to loose!
~🐈~
↬@jastm1🌊
https://www.coursera.org/specializations/data-science-python?utm_medium=email&utm_source=marketing&utm_campaign=2QBGEJZREeajEnVsu251ig
The 5 courses in this #University of #Michigan specialization introduce learners to data science through the python programming language. This skills-based specialization is intended for learners who have basic a python or programming background, and want to apply statistical, machine learning, information visualization, and text analysis techniques to gain new insight into their data.
Introduction to Data Science with Python (course 1), Applied Plotting, Charting & Data Representation in Python (course 2), and Applied Machine Learning in Python (course 3) should be taken in order and prior to any other course in the specialization. After completing those, courses 4 and 5 can be taken in any order. All 5 are required to earn a certificate.
Bizning faxriy oqituvchimiz Sultanov Ruslan Rustamovich
➖➖➖➖
Наш почётный учитель Султанов Руслан Рустамович
#tiue#university#университет
Telegram | Instagram | Website
Congratulations Class of 2027! Welcome to New Uzbekistan University! 🎉
#NewUU2027#NewUzbekistanUniversity#University
Check out the full video on our YouTube!
Best Regards,
NewUU Student Council
Telegarm | Instagram
🇰🇷Janubiy Koreya ta’lim tashkilotlari bilan hamkorlik aloqalari mustahkamlanmoqda
🇺🇿Batafsil
___
Strengthening cooperation with South Korean educational organizations
🇬🇧Eng
___
Укрепление сотрудничества с Южно-Корейскими образовательными организациями
🇷🇺Ru
#GraduateSchool#Soonchunhyang#University#Cooperation
Web-site | Telegram | Facebook | Instagram
Handong Global universiteti bilan hamkorlikni yangi bosqichlari
🇺🇿Batafsil
___
New Stages of Collaboration with Handong Global University
🇬🇧Eng
___
Новые этапы сотрудничества с Глобальным университетом Хандонг
🇷🇺Ru
#GraduateSchool#Handong#Collaboration#University
Web-site | Telegram | Facebook | Instagram