Performance deep dive

Luhn
Luhn in Python

In this approach, we'll find out how to most efficiently validate a number with the Luhn algorithm.

The approaches page lists two idiomatic approaches to this exercise:

  1. Using reversed() with a for loop
  2. Using replace(), reverse, enumerate()

For our performance investigation, we'll also include a third approach that uses recursion.

Benchmarks

To benchmark the approaches, we wrote a small benchmark application using the timeit library.

reversed for:                 1.0783263299963438e-05
replace reverse enumerate:    9.933844099985436e-06
recursion:                    2.4321520800003783e-05

At an avergae time per call of 9934 nanoseconds, the replace(), reverse, enumerate() approach was the fastest. The reversed() with a for loop approach was a bit slower, at 10783 nanoseconds. The recursive approach was much slower, at about 24321 nanoseconds.

20th Nov 2024 · Found it useful?