Skip to content Skip to sidebar Skip to footer

Why Passing A List As A Parameter Performs Better Than Passing A Generator?

I was making an answer for this question, and when I tested the timing for my solution I came up with a contradiction to what I thought was correct. The guy who made the question w

Solution 1:

I have been benchmarking your functions:

enter image description here

from simple_benchmark import BenchmarkBuilder
from random import choice

b = BenchmarkBuilder()
from operator import setitem


@b.add_function()defhow_many_different_lists(lists):
    s = set(str(list_) for list_ in lists)
    returnlen(s)


@b.add_function()defthe_other_function(lists):
    s = set([str(list_) for list_ in lists])
    returnlen(s)


@b.add_arguments('Number of lists in the list')defargument_provider():
    for exp inrange(2, 18):
        size = 2**exp

        yield size,  [list(range(choice(range(100)))) for _ inrange(size)]


r = b.run()
r.plot()

Generators are lazy because generator expression will create the items on the fly in comparison with list comprehension which will create the entire list in memory. You can read more here: Generator Expressions vs. List Comprehension

As you can see from the benchmark there is not such a big difference between them.

Post a Comment for "Why Passing A List As A Parameter Performs Better Than Passing A Generator?"