Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
FJORDS(峡湾) 8K 60FPS
Although a sought-after destination in the summer, the Norwegian fjords lay mostly empty in the winter time. However, this time of year is no less magical. This video aim to show this magic, all in glorious 8K resolutions at 60 fps.
挪威峡湾虽然是夏季的热门目的地,但在冬季时空无一人,在一年中的这个时间的景色同样非常不可思议。此视频旨在以60 fps的出色8K分辨率显示这种魔力。
- 作者: Morten Rustad
- https://youtu.be/0pmvuKzBIqM
频道: @View_4k#8k
Hawaii in 8K ULTRA HD - Paradise of North America (60fps)
This videos you can use for learn Nature, about place, River, Country, City, etc with Ultra-HD resolution.
- 原视频: https://youtu.be/PF1EAtMswPo
- 画质(上面链接): 8K60P
- 作者: 8K World
统计: @View_4k#4k#8k
From Darkness To Light
From Darkness To Light is an 8k Time-Lapse film shot by storm chaser Ty Schmitt. All the clips in the film were captured on the Great Plains during the 2019 spring storm season. Ty traveled over 30,000 miles in 3 months chasing Mother Nature's most intense moments.
All images were shot on a Nikon D850, and edited in LRTimelapse, After Effects, and Premiere Pro.
- 原视频: https://youtu.be/MlIXpZFTBP4
- 画质(上面链接): 8K
- 作者: Ty Schmitt
统计: @View_4k#4k#8k
Hawaii in 8K ULTRA HD - Paradise of North America (60fps)
This videos you can use for learn Nature, about place, River, Country, City, etc with Ultra-HD resolution.
- 原视频: https://youtu.be/PF1EAtMswPo
- 画质(上面链接): 8K60P
- 作者: 8K World
统计: @View_4k#4k#8k
From Darkness To Light
From Darkness To Light is an 8k Time-Lapse film shot by storm chaser Ty Schmitt. All the clips in the film were captured on the Great Plains during the 2019 spring storm season. Ty traveled over 30,000 miles in 3 months chasing Mother Nature's most intense moments.
All images were shot on a Nikon D850, and edited in LRTimelapse, After Effects, and Premiere Pro.
- 原视频: https://youtu.be/MlIXpZFTBP4
- 画质(上面链接): 8K
- 作者: Ty Schmitt
统计: @View_4k#4k#8k
Frankfurt
Frankfurt is a city of great diversity. It is a metropolis of banks and big business shows and shopping on the one side, culture and traditions on the other.
- 原视频: https://youtu.be/UaveL8lp_ws
- 画质(上面链接): 8K
- 作者: Cities in 4K
统计: @View_4k#4k#8k
FJORDS(峡湾) 8K 60FPS
Although a sought-after destination in the summer, the Norwegian fjords lay mostly empty in the winter time. However, this time of year is no less magical. This video aim to show this magic, all in glorious 8K resolutions at 60 fps.
挪威峡湾虽然是夏季的热门目的地,但在冬季时空无一人,在一年中的这个时间的景色同样非常不可思议。此视频旨在以60 fps的出色8K分辨率显示这种魔力。
- 作者: Morten Rustad
- https://youtu.be/0pmvuKzBIqM
频道: @V1_BLOG#8k#view
TelegramUltraPrivateChannel #0042
My old designs in 8 Colors
>> FOR <<
#iPhone14
#iPadAir5
#8K#Desktop
----------------------
Prod. By@Hk3ToN
----------------------