More efficient code, but slower program

Cecil Westerhof Cecil at decebal.nl
Wed Jul 27 08:58:02 EDT 2022


It is not very important, but I am just curious.

Original I had in a program:
    values      = [*range(100)]

But because it is done quite often I expected that initialising:
    range_list  = [*range(100)]

and then use:
    values      = range_list.copy()

Would be more efficient. So I tried:
    timeit('values      = [*range(100)]')
    1.6964535564184189

and:
    timeit('new_values = values.copy()', 'values = [*range(100)]')
    0.6457642465829849

That showed that it should make a positive difference.
But when changing the program it took a little bit more time.
I find the code with the copy a little bit better, so I kept it.
But I am curious why the effect is the opposite of what I expected.
It does not hurt to understand optimisation better, so I can do a
better job when I need it.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof


More information about the Python-list mailing list