Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
https://docs.python.org/3/library/marshal.html#module-marshal
marshal — Internal Python #object_serialization
This module contains functions that can read and write Python values in a binary format. The format is specific to Python, but independent of machine architecture issues (e.g., you can write a #Python value to a #file on a PC, transport the file to a Sun, and read it back there). Details of the format are undocumented on purpose; it may change between Python versions (although it rarely does).
@thefavbot
Qué puede hacer este bot?
Este bot puede recopilar todos sus medios en un solo lugar.
Usted puede acceder a sus medios favoritos en cualquier chat!
Para eso debes escribir @thefavbot en el chat que deseas. Soporta:
Foto, video, archivo, audio, voz, gif.
Para agregar cualquier medio a su colección, solo necesita enviarlo o reenviarlo al bot.
Idioma: Inglés
(visto en @BotsGram_cu)
#gift, #video, #image, #file
#Musicopy#Music#File#Transfer
Join the Musicopy: Music File Transfer beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/Ck9KaZVR
Shared by Dimitri
Sharing
Share files and apps on android to other devices using browser
Share files and apps over HTTP.
You need the other device to be connected to the same network. just toggle on the server and scan the QR Code on other device and you're good to go. Files sent from browser to the app can be found in Sharing/ folder in your internal storage. You can always disable uploads in the app settings.
https://github.com/Ammar64/Sharing
Download
https://github.com/Ammar64/Sharing/releases/latest
https://f-droid.org/packages/com.ammar.sharing/
#share#file#Transfer#Android#qr
@warlockpublicurl_bot
Qué puede hacer este bot?
Envíale cualquier Archivo Multimedia de Telegram y generará un enlace directo para ello
Los Archivos Porno están Estrictamente Prohibidos.
Idioma: Inglés
(visto en @BotsGram_cu)
#file, #upload, #link, #url, #public, #telegram