List comprehension strangeness

Chris Angelico rosuav at gmail.com
Mon Jul 22 11:48:58 EDT 2019


On Mon, Jul 22, 2019 at 11:33 PM Nicholas Cole <nicholas.cole at gmail.com> wrote:
>
> I was profiling a slow function in an application last week, and came
> across something that I still can’t explain. Inside a loop that was being
> called 4 times, inside a for loop that ran for a few dozen times there was
> a list compression of the form:
>
> [x.id for x in some_function()]
>
> According to the profiler, some_function was being called 52,000 times —
> many, many times more than the few dozen it should have been. And sure
> enough, removing the comprehension did indeed speed up the function.
>

Was it actually being CALLED that many times, or was some part of it
being RUN that many times? Try adding an actual counter to the top of
some_function to see how many times it's being invoked.

ChrisA



More information about the Python-list mailing list