TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #32 · 7 фев.

Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять: 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

Резултати

Пронајдени 70 слични објави

Пребарај: #sayyestowasteless

当前筛选 #sayyestowasteless清除筛选
NEA Singapore

@NEASingapore · Post #855 · 07.07.2024 г., 01:02

🚩 Red flag alert 🚩 Say “No” to single-use plastics! Embrace reusable alternatives instead. Every action counts towards a greener future! #SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #717 · 10.12.2023 г., 01:02

Looking forward to festive feasting? Here’s how you can feast ✨smart✨: Order only what you can finish and enjoy the satisfaction of a clean plate and choices well-made 🍴 #SayYesToWasteLess

NEA Singapore

@NEASingapore · Post #312 · 30.01.2022 г., 02:30

Order or cook just enough for you and your guests, to avoid wasting food this Lunar New Year. Let’s also observe safe management measures, to keep ourselves and our loved ones safe. #SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #1169 · 15.11.2025 г., 01:03

🎶 Ooooo~ This is an S.O.S.! 🎶 Good deals may be tempting but just because it’s on discount doesn’t mean you have to buy it. Reduce food wastage during the upcoming year-end festivities: ✅ Plan your meals and prep a shopping list ✅ Order only what you can finish ✅ Transform leftovers into new dishes #SayYEStoWasteLess#SustainableSG

NEA Singapore

@NEASingapore · Post #723 · 16.12.2023 г., 01:00

As the festive clock ticks, let's not forget the ticking dates in our pantry! Place items nearing their expiry dates at the front of your shelves. This helps you remember to use them soon and reduce food wastage. #SayYEStoWasteLess#TowardsZeroWaste

NEA Singapore

@NEASingapore · Post #501 · 04.02.2023 г., 02:01

Have leftover items from your Lunar New Year festivities? Be sure to place food that is near expiry within view, and practise the “First to Expire, First Out” approach when organising your home pantry! #SayYEStoWasteLess#TowardsZeroWaste

NEA Singapore

@NEASingapore · Post #499 · 28.01.2023 г., 02:01

A scrumptious meal with your family and friends doesn’t have to be excessive. If they are visiting other places beforehand, check with them first on how much they can eat. Let’s cook or order only what we can finish, to avoid food waste! #TowardsZeroWaste#SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #496 · 24.01.2023 г., 01:30

If you have extra steamboat ingredients from Lunar New Year gatherings, store these leftovers properly to keep them fresh for a longer time and avoid food wastage! More tips at www.nea.gov.sg/food-waste-management-strategies #TowardsZeroWaste#SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #447 · 22.10.2022 г., 01:30

Collecting more candy than we can finish this Halloween is less of a treat and more like a trick that leads to food waste! Say no to excessive candy, just like how you should only order and cook what you can eat. #SayYEStoWasteLess#TowardsZeroWaste

123•••56
ПретходнаСтраница 1 од 6Следна