So, I was busy in standby mode with recursion, and I noticed that a loop using recursion was much slower than a regular while loop, and I was wondering if anyone knew why. I included the tests I did below:
>>> import timeit >>> setu="""def test(x): x=x-1 if x==0: return x else: test(x) """ >>> setu2=""" x=10 while x>0: x=x-1 """ >>> timeit.timeit(stmt="test(10)",setup=setu,number=100) 0.0006629826315997432 >>> timeit.timeit(stmt=setu2,number=100) 0.0002488750590750044 >>> setu="""def test(x): x=x-1 if x==0: return x test(x) """ >>> timeit.timeit(stmt="test(10)",setup=setu,number=100) 0.0006419437090698921
However, during the last test, I noticed that if I took out the
else , it showed a slight speed improvement, so I wonder if the if statement is the cause of this difference in loop speeds?
IT Ninja
source share