Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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 10 Benefits of Peanuts 🥜
(Groundnut or Mungfali)
1. Good for healthy Brain(Omega 3 & 6 fatty acids)
2. Protects from Heart disease
3. Fights Stomach Cancer
4. Good for healthy Hair Growth
5. Reduces bad Cholesterol
6. Fights against Depression
7. Good for healthy & Glowing Skin
8. Fights free-radicals (Anti-inflammatory)
9. Rich in Proteins & Fats(good)
10. Contains ample fiber
Nutrients available : Proteins, Vit. E, Minerals like Potassium, Magnesium, Phosphorus, Sodium & Zinc. Omega 3 & 6 fatty acids.
Nutritional Value per 100g
Calories : 567kcal
Protein : 26gm
Fats : 49gm
Bottom line : There's no reason not to munch on this cheaply available yet full of nutrition, crunchy & nutty peanuts. It's a boon for optimum health & wellness.
#foods
🚨Source : @HeathSafetyTps
Herbal Tea
Herbal tea is a decoction or infusion of herbs & spices.
There is a herbal tea for everything. Green tea is a great energy-boosting alternative to coffee, chamomile helps you go to sleep, fennel & peppermint teas aid digestion. Others are ginger, tulsi, even pepper & cinnamon, all extremely healthy.
So, make a good habit of drinking herbal teas.
#foods
⚠️ Also look at: Benefits of GINGER TEA
🚨Source: @HeathSafetyTps
Ginkgo Biloba - 🧠 herb
It's a leaf of the ginkgo tree, which is native to China & one of the oldest plants on the planet, having potential to treat Alzheimer's disease & age-related mental decline.
It's believed that it works by thinning the blood & thereby improving oxygen flow to the brain. The brain is a glutton for oxygen, so it's possible that even a slight lack of circulation can affect its performance.
Gingko improves both attention & memory, but as a brain booster for people with normal mental abilities, it remains controversial.
#foods
🚨Source: @HeathSafetyTps
Diet tips for Gum Health
What a person eats can directly affect the health of their teeth & gums. The foods that should be incorporated in your diet:
1. High-fiber fruits & vegetables, as these can help clean up the mouth, especially Apple🍎 & Ginger
2. Black & Green teas, which help reduce bacteria
3. Dairy products (such as milk, cheese, & yogurt) , as these foods help increase saliva production
4. Foods that contain fluoride, which include water & some poultry & seafood products
5. Sugar-free gum, as chewing it will increase saliva production
It's best to avoid these foods & beverages:
1. Alcohol , as it can dry out the mouth
2. Starchy foods that become stuck in the teeth
3. Sticky candies & sweets
4. Carbonated soft drinks that contain phosphoric & citric acids as well as sugar
#foods
🚨Source : @HeathSafetyTps
HEALTH TIPS:
Liver Detox Juice
Whenever you've a big night out or a heavy cheat meal, you can try a big juice full of fruit & vegetables with liver loving nutrients.
Relish this simple liver cleansing juice...
1 large carrot
1 beetroot
1 green apple
2 cups kale or spinach
1 grapefruit or orange
1 knob of ginger
1/2 cup water
Clean the fruit & vegetables before juicing.
Dilute with half a cup of water or add ice to your juice.
#foods
Source: @HeathSafetyTps
HEALTH TIPS:
Ginkgo Biloba - 🧠 herb
It's a leaf of the ginkgo tree, which is native to China & one of the oldest plants on the planet, having potential to treat Alzheimer's disease & age-related mental decline.
It's believed that it works by thinning the blood & thereby improving oxygen flow to the brain. The brain is a glutton for oxygen, so it's possible that even a slight lack of circulation can affect its performance.
Gingko improves both attention & memory, but as a brain booster for people with normal mental abilities, it remains controversial.
#foods
Join our community today @HeathSafetyTps
Please share now
Diet tips for Healthy Gum
What a person eats can directly affect the health of their teeth & gums. The foods that should be incorporated in your diet:
1. High-fiber fruits & vegetables, as these can help clean up the mouth, especially Apple🍎 & Ginger
2. Black & Green teas, which help reduce bacteria
3. Dairy products (such as milk, cheese, & yogurt) , as these foods help increase saliva production
4. Foods that contain fluoride, which include water & some poultry & seafood products
5. Sugar-free gum, as chewing it will increase saliva production
It's best to avoid these foods & beverages:
1. Alcohol , as it can dry out the mouth
2. Starchy foods that become stuck in the teeth
3. Sticky candies & sweets
4. Carbonated soft drinks that contain phosphoric & citric acids as well as sugar
#foods
Join 👉🏻@HealthSafetyTips