Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
🛜🔠🔠🔠🔠🔠
🔠🔠🔠🔠
💛 Alkimyogar
Bu kitobni qancha kop maqtasam arziydi! Qayta qayta tinglang Va o'qing!
Va albatta barcha ORZU maqsadlaringiz Amalga oshganda bizni ham albatta tabassum bilan eslab qo'ying
🤍
🤍 SİZ SO'RAGAN AUDİO KİTOB!
#audiobook
💛@Biglibrary_uz
🔠🔠🔠🔠🔠🔠🔠🔠
🎙 Ichindagi ichindadur
💡 Hayrlı kun kitobsevar qadrdonlarim!! Sizga Juda zo'r
#audiobook🎧 bilan keldim.
Albatta tinglang! Juda ham zo'r kitob! Qancha tariflasam , shuncha so'zlar ojizlik qiladi! Ming marta maqtagandan ko'ra bir marta o'zingiz mazasini tatib koring 🫂
Bu kitobni o'qiganlar Yoki tinglaganlar bormi ,
🔥 reaksiyalarni bosib qoying
@Milliarderlarim
#Narratorr#Audiobook#amp#TTS
Join the Narratorr - Audiobook & TTS beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/Fv19nvDd
Shared by Dimitri
📖Title : The Frozen River
✍️Author : Ariel Lawhon
⭐️Rating : 4.38/5 (Goodreads)
📆Published : Dec 05, 2023
————————————————
Summary:The Frozen River by Ariel Lawhon is a historical mystery set in 1789 Maine. Midwife and healer Martha Ballard is called to examine the body of a man found trapped in the frozen Kennebec River. While authorities quickly declare the death an accident, Martha suspects something far darker. As she records events in her diary and follows the clues, she uncovers a web of violence, secrets, and injustice involving powerful members of the community. Determined to seek the truth despite threats and social pressures, Martha risks her reputation and safety while fighting for justice in a society where women’s voices are often ignored.
————————————————
#fiction#mystery#audiobook#historical#thriller#ariellawhon#thefrozenriver@Bookslibraryofficial
📖Title : More Days at the Morisaki Bookshop
✍️Author : Satoshi Yagisawa
⭐️Rating : 3.85/5 (Goodreads)
📆Published : Dec 06, 2011
————————————————
Summary:More Days at the Morisaki Bookshop follows Takako as she continues healing while living above her uncle’s secondhand bookshop in Tokyo’s Jimbocho district. Surrounded by books and familiar faces, she confronts lingering grief, evolving relationships, and quiet uncertainties about the future. The novel focuses on small, meaningful moments, showing how literature, routine, and human connection gently restore a sense of belonging. Through everyday interactions, it portrays healing as gradual, imperfect, and deeply tied to community, memory, and the comforting presence of books.
————————————————
#fiction#japan#cozy#audiobook#romance#moredaysatthemorisakibookshop#satoshiyagisawa@Bookslibraryofficial@free_novellas@eternalmantra
📖Title : Bemused
✍️Author : Farrah Rochon
⭐️Rating : 3.92/5 (Goodreads)
📆Published : Jan 07, 2025
————————————————
Summary:Five sheltered sisters living in a quiet seaside village learn that they are the legendary Muses, daughters of Mnemosyne, Goddess of Memory. After their mother is kidnapped by Hades, the sisters are forced to leave their protected lives behind. Guided by Calliope’s leadership, they journey through dangerous lands, face mythical trials, and uncover their divine powers. Along the way, they confront fear, doubt, and destiny itself. Through music, storytelling, courage, and unity, the sisters strengthen their bond and transform from overlooked performers into heroic figures, embracing their true identities and shaping their own legendary “gospel truth.”
————————————————
#fantasy#mythology#retellings#fiction#historicalfiction#audiobook#bemused#farrahrochen@Bookslibraryofficial@free_novellas@eternalmantra