Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Weekend
Let's begin,
Feet on feet
Following each other
Across the room,
Like a fleet
Unrequited and washed up
At shores
Unreachable and silent dead
Now pace up,
Reach my hand
Sigh
And burn
With violent fumes,
Find me a blink away
In carpeted elevators
Locked
In gaze
Finally,
Race me to the longest yard
At 3
Past midnight,
Rest on this hammock
Of tacit fears
And inhibitions,
Ask me
If I know myself,
I'll pause
And say
More each day
When I'm with you.
#review#poetry#ap
I've been thinking of life
And it was raining season
Life is worse than the hell
Why? Couldn't get reason
How and when will i get rid
From this unbearable pain
People can shouting loudly
I could not cry in the rain
#ap#review#shortpoem
Tanka : 57577
I'm alone at my place
Perhaps, someone will come here
A beautiful lady, and
Will take my hand in her hand
Maybe will say I'm with you.
#ap#review#tanka
Tanka : 57577
If I do any crime!
If I hurt you more before:
Will you forgive me?
Like you forgave me before;
I like you because of these.
#ap#tanka#review
I sniffed our wilted pink roses
When thy old letters, I dupp'd
Haue not rights to touch thou
To hug, To kiss thou forehead
#Ap#quatrain#review
Words : Old/Middle into Morden English
Thy - your
dupp'd -opened
Haue/Hast not - have not
Thou - you (subject)
• Quatrain •
The world can't see inside's pain
And, tears are hidden in the rain
Even if the world calls me stupid
But, Her voice affects like music
#ap#quatrain#review
#NATO
Jens #Stoltenberg (#Ap|S&D): “Onorato dalla decisione degli Stati NATO di estendere il mio mandato come Segretario Generale fino al 1° ottobre 2024. Il legame transatlantico tra Europa e Nord America ha garantito la nostra libertà e sicurezza per quasi 75 anni e, in un mondo più pericoloso, la nostra Alleanza è più importante che mai.”
@OsservatorioEsteri