Reversing a string in Python with Performance Benchmarking

Recently I’ve been putting a lot of time into brushing up my Python knowledge for big data projects and operations. For a task that’s so simple I’ve found reversing a string can be quite enlightening for how to better “think in Python”.

As an example, here’s how I would have previously reversed a string before really digging into the Python language:

Quite less than ideal!

After digging a bit further I learnt about slice notation in Python – and it’s amazing. This StackOverflow question serves as a good primer, here’s the core answer from that question for future reference as well:

There is also the step value, which can be used with any of the above:

The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default).

The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning. So:

So what does this mean for reversing a string? Actually, quite a lot – that means we can now take our original statement above and re-write it simply as:

But how about performance? Python is commonly used on big data after all. Let’s introduce a couple of other ways to accomplish this task in Python and then benchmark them against each other:

Another Python specific approach for this task would be the reversed() function

We could also use a generator function, one of the more friendly ways of writing this as it reads as it performs – join all the i-th-s elements of the string where i goes from the len of the string to zero.

We could also use a deque object:

But what about performance? Using timeit let’s quickly benchmark these against each other:

Original function

In [250]: %timeit reverse_codingo(“reverse”)
100000 loops, best of 3: 3.61 µs per loop

Slice Operator

In [243]: %timeit “reverse”[::-1]
1000000 loops, best of 3: 310 ns per loop

Reverse Function

In [241]: %timeit reverse(“reverse”)
100000 loops, best of 3: 3.98 µs per loop

Deque Reverse Function

In [244]: %timeit reverse_deque(“reverse”)
100000 loops, best of 3: 2.61 µs per loop

The clear performance winner in speed appears to be the slice operator, also the one which is syntactically the most simple once you’re familiar with it. Definitely an operator worth learning more about and including in the toolkit!

Leave a Reply

Your email address will not be published. Required fields are marked *