Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
#Advert
My online marketing "secret weapon"
Hi there,
I just wanted to shoot you a quick update about a killer
tracking and optimization platform called ClickMagick:
https://clickmagick.com/go/Tajedo
It helps you to scientifically track and optimize all
your ads and promotions, all in one place ...
... and get more leads,conversions and revenues from
the same traffic you're already getting.
There's nothing else like this out there. Check out the
free trial and let me know what you think:
https://clickmagick.com/go/Tajedo
You can Read our Affiliate Disclosure.
#Advert
Software as a Service (SAAS) tool for business owner & Marketers
GrowMeOrganic
GrowMeOrganic is an all-in-one sales automation platform that helps you find verified business emails of your potential clients and send email sequences with automated email follow-ups.
Features:
✅ Extract unlimited emails from LinkedIn search results and export them in form of CSV
✅ Get access to 15 Million B2B company databases across the world which you can filter by a specific Industry and Country
✅ Find contact details of all the employees from any company
✅ Extract contact details of the local business list on google my business
✅ Send unlimited cold emails with automated follow-ups.
✅ Use our email warm-up system to avoid landing your emails in spam
Try GrowMeOrganic
#Advert
Business owners, product creators, service providers, coaches, retailers, ecommerce site managers, virtual assistants...
No matter who you are, if you're selling an offer online, you need a high-converting sales page.
And our brandable course, How to Create Sales Pages that Convert, walks through each essential step needed to put together a sales page that converts visitors to paying customers.
The package is one of our full Blaze course kits so it includes a Course Book, Action Guide, Cheat Sheet, Slideshow, Lead Magnet, Follow-Up Emails, Blog Posts, and more.
What's the weekend special?
Course: How to Create Sales Pages that Convert
Dates: Friday, October 14th to Monday, October 17th
Discount: 50% Off
NEW Upgrade Pack: Quizzes and Sale Copy
Upgrade Bonus: Social Media Images
#Advert
My online marketing "secret weapon"
Hi there,
I just wanted to shoot you a quick update about a killer
tracking and optimization platform called ClickMagick:
https://clickmagick.com/go/Tajedo
It helps you to scientifically track and optimize all
your ads and promotions, all in one place ...
... and get more leads,conversions and revenues from
the same traffic you're already getting.
There's nothing else like this out there. Check out the
free trial and let me know what you think:
https://clickmagick.com/go/Tajedo
You can Read our Affiliate Disclosure.
#Advert
#photoediting#graphicdesign
Even if you don’t know Photoshop, you can work on pictures with great design.
With the help of thousands of design templates on this site,
you can easily create booklets, logos, promotional images, packaging, presentations, promotional images, invitations, infographics and...
many other types of design images.
LINK 👉Canva