python programming python optimization for loop in python

Python's tales from the for-loop: when performance does matter

Spoiler alert! We will talk about list construction, memory efficiency, function/variable execution and conditions.

Spoiler alert! We will talk about list construction, memory efficiency, function/variable execution and conditions.

In this article, we’ll look at some of the most common practices that can have a detrimental impact on performance.

It will focus on python, but many aspects might concern other programming languages too.

List construction

The encountered case

We can often find a for loop that appends content to a list using the append function. We will compare the performance of such a loop with two other methods: list comprehension and list-map-lambda.

Illustration by the author.

Illustration by the author.

As you can see here, list comprehension is quite faster than the other methods. But in defense of the list-map-lambda, it does have to call a lambda function on each iteration which isn’t the case for the two other tested methods.

When having to call a function

Let’s try to even things out by calling functions each time.

Illustration by the author.

Illustration by the author.

As you can see, it didn’t change much for the list-map case to use a function instead of a lambda. As for comparing with list-appending and list-comprehension, list comprehension is still faster, but list-appending is a bit slower than list-map-func or list-map-lambda.

Accessing outer variables, is it fast?

By outer variable I mean using inside a loop something that was defined outside the loop and won’t change while iterating.

First test case, accessing the content of a dictionary

Illustration by the author.

Illustration by the author.

Has you can see, there is quite a big performance difference between accessing the content of the dictionary in the loop and storing it beforehand inside a temporary variable.

As accessing the content of a dictionary isn’t very speedy you should avoid doing it inside your loops if you knowfor sure that the value won’t change while iterating.

Second test case, accessing the content of an object.

We will call here a “temporary” value a variable used to store an intermediate result / the result of an expression. “shortcut” will be used to designate a variable used to access a sub-object.

We will benchmark five cases here.

  • accessing a direct attribute of an object inside the loop,
  • accessing an indirect attribute of an object inside the loop,
  • using a temporary value to store the content of a direct attribute,
  • using a shortcut to access an indirect attribute,
  • (using a temporary value to store an indirect attribute won’t be tested here as the expected performance would be quite the same as using a temporary value for a direct attribute)

Illustration by the author.

Illustration by the author.

What we can conclude from those benchmarks:

  • accessing an attribute inside a loop has non-negligible performance cost, you should avoid it if you can store the content inside a temporary variable,
  • using a shortcut did not help us to be faster and even slowed us down.

As the shortcut being slowest was quite a surprise for me, I did other tests.

First I tested created the shortcut outside the tested function.

Illustration by the author.

Illustration by the author.

In this case the shortcut did help gain a bit of performance.

I was thinking that maybe it was about the time taken to create the shortcut itself and did other tests with the total number of iterations staying the same, but the number of shortcut creation changing.

There isn’t much differences.

I will conclude on that by saying that you should do your own benchmarks to check whether or not using a shortcut is a good idea for your own use case.

(And I’ll make a note to look into it to understand it better.)

Do you REALLY need to iterate over a LIST?

A for loop in python does not need to iterate over a list, but over an iterable. This distinction can help gains memory efficiency.

Lets give some definitions:

  • An iterator is an object allowing you to access one element at a time. To be iterable an object must implement the __next__() method that will give access to the **next element **until there is no more.
  • An iterable is an object that can be create an iterator, it needs to implements the __iter__() method which will return an iterator.
  • A generator is a function that contains the yield statement. It is usable as an iterator. (You can also obtain a generator using the one-liner generator comprehension syntax).

HOW to use a generator?

You can use a generator either using the next(…) function or directly in a loop.

Illustration by the author.

Illustration by the author.

But not let’s get to the import point.

WHY using a generator?

Let’s make two other benchmarks.

In the first case we will construct a first list and use it to build a second one.

Illustration by the author.

Illustration by the author.

In the second case, we will use a generator instead of the first list and then use it to build the list.

Illustration by the author.

Illustration by the author.

As you can see there is quite the difference replacing the first list by a generator helped us to get 1.2x times faster.

Why was it faster? It’s mostly because we didn’t spent time here to construct a first list with it’s memory allocation.

But what matter the most is not that is was faster, it is that in the end we only allocated one list instead of two. When working with huge datasets memory is often the first issue we have to deal with. Using generators instead of lists is so much helpful for those cases as we don’t need to store all intermediary results in memory but only process them as we consume them.

For loop and conditions… not a so good combination

Avoid them when necessary

Each condition has a cost in term of processing time. When you are in a loop this cost will accumulate for each iteration.

So **when performance does matter **and you can, put the conditions outside the loop.

Illustration by the author.

Illustration by the author.

Illustration by the author.

Illustration by the author.

Inside vs outside, we gained a bit of performance at the expense of our code being a bit less “elegant”.

This method can be used as long as the condition result is always the same for each iteration of the same loop.

A frequent case of condition in a loop that can be avoided is handling the first and/or last iteration differently.

We will start by benchmarking the case with the conditions inside the loop

Illustration by the author.

Then when we handle the first and last element outside the loop.

Illustration by the author.

We can notice the performance gain.

Last illustration won’t contain a benchmark, it is to show you how, when using a generator, you can do a specific processing for the first element, but still have it while iterating the loop using itertools.chain.

Condition’s order can have an impact

When you have independent conditions, that is to say when you can change the order of the conditions in a if — elif case, choosing the order of the conditions can have an impact.

Let’s consider three variables: a, b, and c. When we encounter a multiple of 10, we increment a, when it is an odd number we increment b, and in other cases we increment c

If we consider the first 10 numbers, it would give us:

a = 1, b = 5, c = 4

Let’s benchmark it, shall we?

Illustration by the author.

The first benchmark will be used as reference, the first condition is the one we will enter the less, the second one correspond to the case that will happen most often.

eIllustration by the author.

In the second benchmark, we reversed the two first conditions to have the most frequent case first. We can note a non-negligible gain in performance. Why ? Because by putting the odd/even check first, we needn’t to perform the multiple of ten check for half the cases.

Illustration by the author.

A third benchmark, the odd/even case is still first, but we reversed the logic to have the condition for the next more frequently occurring case (the “other case”, that is to say neither odd neither a multiple of ten).

While it is still faster than the first benchmark, it is a bit less more slow than the second one. It’s because it is faster to perform an equality check than an inequality one.


That’s all folks!