Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
¿Qué puede hacer este bot?
🤖@BajarVideosBot
📎 Este es un potente bot para descargar videos de diferentes plataformas
▪️Sitios soportados:
Youtube.com
Facebook.com (Cuentas Publicas)
TikTok.com
Twitter.com
Vimeo.comPinterest.com
Otros Sitios
#Herramienta#Descargar
( Visto en: @BotsGram_Cu )
¿Que puede hacer este bot?
🤖@ttloaderbot
📎El bot descarga vídeos de TikTok en la mejor calidad y sin marca de agua.
#Descargar#Herramienta
( Visto en: @BotsGram_Cu )
¿Que puede hacer este bot?
🤖@VideoDownloadBot
📎El bot te permite descargar vídeos de TikTok, YouTube, VK, Instagram, Twitter y de otros 700 sitios.
#Descargar#Herramienta
( Visto en: @BotsGram_Cu )
¿Que puede hacer este bot?
🤖@YtbDownBot
📎Soy YTBdownbot . Puedo descargar videos de YouTube y TikTok .
El bot funciona directamente y en los chats . Agrega el bot a un grupo, luego envía el enlace del video y el bot enviará el video al chat.
#Descargar#Herramienta
( Visto en: @BotsGram_Cu )
¿Que puede hacer este bot?
🤖@TGStoryXBot
📎Puede descargar fácilmente historias de Telegram y publicaciones archivadas de cualquier usuario en alta calidad y velocidad a través de su enlace.
#Descargar#Herramienta
( Visto en: @BotsGram_Cu )
¿Que puede hacer este bot?
🤖@Kitefileupbot
📎Con este bot podrás descargar contenido de múltiples sitios en varios formatos y escucharlo en cualquier momento
sitios web compatibles: (youtube, instagram, facebook, twitter, tiktok, likee, pinterest, snapchat).
#Descargar#Herramienta
( Visto en: @BotsGram_Cu )
¿Que puede hacer este bot?
🤖@downloadStickersBot
📎Descargador de stickers, descarga cualquier stickers de Telegram
#Sticker#Descargar
( Visto en: @BotsGram_Cu )
¿Que puede hacer este bot?
🤖@InstagramDlPro_Bot
📎Puedo descargar fotos, videos, reels, Albums, Tv y stories de instagram si es publico, solo mandame el link aqui.
También puedo trabajar en canales, solo necesitas enviar ese enlace y yo enviaré la publicación y eliminaré ese enlace.
#Descargar#Instagram#Herramienta
( Visto en: @BotsGram_Cu )
🤖Nuevo bot
📋 Nombre: SpotSeekBot
🆔 Nombre de usuario: @SpotSeekBot
⭐️ Calificación: ⭐️⭐️⭐️⭐️ (4.7/5 de 340 votos)
————————————————————
ℹ️Descripción: Descarga tu música preferida de Spotify temas sueltos, albums o playlists.
🌐 Idiomas: inglés
💬 Soporta en línea: No
👥 Grupos: si
#️⃣ Etiquetas: #descargar#música#Spotify
¿Que puede hacer este bot?
@mysterious_uploader_robot
•Cargador de URL
•Cargar varios tipos de formatos
•Descargar enlaces de más de 2 GB
•Enlaces directo y los sube a Telegram como un archivo/video.
Idioma : Inglés
#upload#descargar#download
( Visto en: @BotsGram_Cu )
@Instatoolsbot
¿Qué puede hacer este bot?
Con este bot puede descargar reels, publicaciones, videos, historias, IGTV y más de Instagram.
Idiomas: Inglés y árabe
Nota: Es importante usar Telegram Direct para acceder a este bot.
(Visto en @BotsGram_cu)
#instagram#medios#descargar