I have below two functions:
def foo(n=50000):
return sum(i*i for i in range(n)) # just called sum() directly without
def bar(n=50000):
return sum([i*i for i in range(n)]) # passed constructed list to sum()
I was hoping that foo
will run faster then bar
but I have checked in ipython with %%timeit
that foo
is taking slightly longer then bar
In [2]: %%timeit
...: foo(50000)
...:
100 loops, best of 3: 4.22 ms per loop
In [3]: %%timeit
...: bar(50000)
...:
100 loops, best of 3: 3.45 ms per loop
In [4]: %%timeit
...: foo(10000000)
...:
1 loops, best of 3: 1.02 s per loop
In [5]: %%timeit
...: bar(10000000)
...:
1 loops, best of 3: 869 ms per loop
The difference increases as I increase value of n hence I tried to check function with dis.dis(foo)
and dis.dis(bar)
but it was identical.
So what would be the cause of such time difference between both methods?