Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
👑 Top discounts and deals from AMAZON:
➡️AMAZON In Germany
➡️AMAZON in Spain
➡️AMAZON in France
➡️AMAZON in Italy
➡️AMAZON in United Kingdom
➡️AMAZON in the Netherlands
➡️AMAZON in Belgium
➡️AMAZON in Poland
➡️AMAZON in Sweden
⭐️The best sales & deals online!@BestenDeals
#Amazon#kws
⭐️Special offer from AMAZON:
➡️Tshirt Women Oversize Shirt Women Tops Summer
➡️https://amzn.to/4w4GoxW
💶 14.99€-> 12.74€ (-15%) ✨Ends in 15 hours
⭐️The Best Offers & Deals in EuropeOnline: ➡️@BestenDeals
#Amazon#kws
👑 Top discounts and deals from AMAZON:
➡️AMAZON In Germany
➡️AMAZON in Spain
➡️AMAZON in France
➡️AMAZON in Italy
➡️AMAZON in United Kingdom
➡️AMAZON in the Netherlands
➡️AMAZON in Belgium
➡️AMAZON in Poland
➡️AMAZON in Sweden
⭐️The best sales & deals online!@BestenDeals
#Amazon#kws
👑 Top discounts and deals from AMAZON:
➡️AMAZON In Germany
➡️AMAZON in Spain
➡️AMAZON in France
➡️AMAZON in Italy
➡️AMAZON in United Kingdom
➡️AMAZON in the Netherlands
➡️AMAZON in Belgium
➡️AMAZON in Poland
➡️AMAZON in Sweden
⭐️The best sales & deals online!@BestenDeals
#Amazon#kws
⭐️Promotional offer from AMAZON:
➡️Ring Indoor Camera (2nd Gen.) | Surveillance camera for indoor use | 1080p HD video, privacy screen protection, Wi-Fi, ideal for pets
➡️https://amzn.to/47glRLi
💶 49.99€-> 34.99€ (-30%) 🎉1,000+ purchased
⚠️The quantity and duration of the offer are limited!#Amazon#kws
⭐️The best offers & deals online!➡️@BestenDeals
⭐️Promotional offer from AMAZON:
➡️UGREEN Nexode Power Bank 20000mAh, 165W Fast Charging, 65cm Retractable Cable, Compatible
➡️https://amzn.to/4qAG3A1
💶 89.99€-> 59.99€ (-33%) 🎉ends in 14 hours
⚠️The offer quantity and duration are limited!#Amazon#kws
⭐️The best offers & deals online!➡️@BestenDeals
⭐️Promotional offer from AMAZON:
➡️KONO 55cm Hand Luggage Case Trolley Set 2 Pieces Luggage Sets, Small Case with Wheels Hand Luggage Set with Ryanair Travel Bag 40x20x25cm
➡️https://amzn.to/4pQQK0g
💶 59.99€-> 50.98€ (-15%) 🎉
⚠️The quantity and duration of the offer are limited!#Amazon#kws
⭐️The best offers & deals online!➡️@BestenDeals
⭐️Aktionsangebot von AMAZON:
➡️Collagen Pulver 1 kg – Kollagenhydrolysat Peptide Typ I, II & III – Geschmacksneutrales Eiweißpulver – Made in Germany – Wehle Sports (1000g (1er Pack)
➡️https://amzn.to/4bv5yxL
💶 39,99€-> 30,59€ (-24%) 🎉10.000+ sell
⚠️Angebotsmenge und -dauer sind begrenzt!#Amazon#kws
⭐️Die besten Angebote & Deals online!➡️@BestenDeals
⭐️Promotional offer from AMAZON:
➡️Glückstoff® Orthopaedic Pillow (Certified for all Sleep Types) Pillow for Neck Pain made from Memory Foam | Neck Support Pillow Ergonomic Head Pillow Side Sleeper Pillow Grey
➡️https://amzn.to/3LEsBM7
💶 89.90€-> 67.91€ (-24%) 8.000+ purchased🎉
⚠️The quantity and duration of the offer are limited!#Amazon#kws
⭐️The best offers & deals online!➡️@BestenDeals
⭐️Special offer from AMAZON:
➡️1. JACK & JONES Men's Blouson Jacket
💶 49.99€ -> 20.30€ (-59%) ✨
➡️2. Men's Straight Leg Joggers, Long Pants with Open Hem, Loose Fit Sports Pants, Comfortable Training Pants
💶 59.98€ -> 29.31€ (-51%) ✨
⭐️The best offers & deals in Europeonline:
➡️@BestenDeals
#Amazon#kws#look