Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
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
Potato Waffle Burger 🍔🥔
Ingredients:
- 6 potatoes 🥔
- 70g all-purpose flour 🌾
- 100 ml plant drink 🥛
- 1 tsp salt 🧂
Toppings:
- 2 spreads of vegan cream cheese 🧀
- 1 handful of lamb's lettuce 🥬
- 5 mushrooms 🍄
- Fried onions, chili 🌶
- Agave mustard dressing 🍯
Dressing:
- 2 tbsp mustard
- 3 tbsp agave syrup 🍯
- 1 tbsp oil 🫒
- 1 tbsp water 💧
- Pinch of salt, pepper 🧂
Preparation:
1. Grate the potatoes, squeeze out the liquid, and mix with all ingredients for the dough. 👩🍳🥔
2. Fry the mushrooms and season them. Mix the ingredients for the agave mustard dressing. 🍄
3. Pour the batter into the waffle iron. 🧇
4. Enjoy with the toppings! 😋
#PotatoWaffleBurger#VeganBurger#PlantBased#HealthyEats#EasyRecipes
@dishes
Potato Waffle Burger 🍔🥔
Ingredients:
- 6 potatoes 🥔
- 70g all-purpose flour 🌾
- 100 ml plant drink 🥛
- 1 tsp salt 🧂
Toppings:
- 2 spreads of vegan cream cheese 🧀
- 1 handful of lamb's lettuce 🥬
- 5 mushrooms 🍄
- Fried onions, chili 🌶️
- Agave mustard dressing 🍯
Dressing:
- 2 tbsp mustard
- 3 tbsp agave syrup 🍯
- 1 tbsp oil 🫒
- 1 tbsp water 💧
- Pinch of salt, pepper 🧂
Preparation:
1. Grate the potatoes, squeeze out the liquid, and mix with all ingredients for the dough. 👩🍳🥔
2. Fry the mushrooms and season them. Mix the ingredients for the agave mustard dressing. 🍄
3. Pour the batter into the waffle iron. 🧇
4. Enjoy with the toppings! 😋
#PotatoWaffleBurger#VeganBurger#PlantBased#HealthyEats#EasyRecipes
@dishes
Fillo Quiche Cups Recipe🥚🥓🧈
Perfect for brunch or appetizers!
Ingredients:
Fillo Dough Shells:
📜 250g Fillo pastry sheets
🧈 50g butter, melted
Filling:
🥓 200g Pancetta or bacon, diced
🥚 10 Large eggs
🌿 50g Fresh chives, chopped
🧂 Salt/Pepper to taste
🧀 150g Swiss & Gruyere cheese
🧀 150g Fresh Mozzarella cheese, sliced
⚪️ Sesame seeds
Instructions:
1️⃣ Preheat oven to 190°C (375°F).
2️⃣ Cut fillo sheets into squares, brush each layer with melted butter, and stack them in a muffin tin.
3️⃣ In a bowl, whisk eggs 🥚, add pancetta 🥓, chives 🌿, and cheese 🧀. Season with salt and pepper 🧂.
4️⃣ Pour mixture into fillo shells, top with mozzarella slices, and sprinkle sesame seeds ⚪️.
5️⃣ Bake for 15–20 minutes or until golden brown ✨.
#EasyRecipes#BrunchGoals#MiniQuiches#CheeseLovers🥧
@dishes
Roasted Zucchini Pepper Pasta🍝🥒🌶️
Ingredients:
🥒 1 zucchini, grated
🌶️ 1 bell pepper
🧅 3 shallots
🧀 100 g cream cheese
🍁 40 ml maple syrup
🧂 1 tsp salt
🫒 Oil as desired
🌿 1 handful of parsley, chopped
🍝 250 g pasta
Preparation:
1️⃣ Put zucchini, bell pepper, and onions in a casserole dish 🥘.
2️⃣ Add cream cheese 🧀, oil 🫒, maple syrup 🍁, and salt 🧂.
3️⃣ Roast everything in the oven for 35 minutes (top/bottom heat) 🔥.
4️⃣ Cook the pasta 🍝.
5️⃣ Mix the roasted vegetables, pasta, and parsley 🌿. Enjoy! 😋
#EasyRecipes#VegetarianPasta#RoastedVeggies#ZucchiniLovers#QuickMeals#ComfortFood
@dishes
Creamy Tuscan Chicken🍗🍅🌿
Ingredients:
- 2 lb chicken breast 🍗
- Salt and pepper to taste 🧂
- 3 tablespoons flour 🌾
- 1 tbsp smoked paprika 🌶️
- 2 tablespoons butter 🧈
- 2 tablespoons olive oil 🫒
- 3 garlic cloves 🧄
- 2 shallots 🧅
- 1 sprig of cherry tomatoes 🍅
- 1/4 cup sundried tomatoes 🍅
- 1/4 cup parmesan cheese 🧀
- 1 teaspoon Italian oregano 🌿
- 1 cup chicken broth 🍲
- 1/2 cup white wine 🍷
- 2 cups heavy/whipped cream 🥛
- 2 cups fresh baby spinach 🥬
Steps:
1. Season chicken with salt, pepper, and smoked paprika. Coat with flour.
2. Heat butter and olive oil in a pan. Sear chicken until golden. Remove and set aside.
3. Sauté garlic, shallots, and cherry tomatoes in the same pan. Add sundried tomatoes.
4. Pour in white wine and chicken broth. Simmer and reduce.
5. Stir in heavy cream, parmesan, and oregano. Cook until thickened.
6. Add baby spinach. Return chicken to the pan and simmer until cooked through.
Serve hot and enjoy! 🍴✨
#CreamyTuscanChicken#ChickenDinner#ComfortFood#TuscanFlavors#EasyRecipes#FoodLover
@dishes