Thursday, July 28, 2016

Map Vs List Comprehension

Case 1. Map Vs List comprehension for user defined function
:~ sadatravu$ python -mtimeit -s'xs = xrange(10)' 'def ch(x): return x+10' 'map(ch ,xs)'
1000000 loops, best of 3: 1.3 usec per loop
:~ sadatravu$ python -mtimeit -s'xs = xrange(10)' 'def ch(x): return x+10' '[ch(x) for x in xs]'
1000000 loops, best of 3: 1.39 usec per loop

Case 2. Map Vs List comprehension for inbuilt function
:~ sadatravu$ python -mtimeit -s'xs = xrange(10)'  'map(hex,xs)'
1000000 loops, best of 3: 0.926 usec per loop
:~ sadatravu$ python -mtimeit -s'xs = xrange(10)'  '[hex(x) for x in xs]'
1000000 loops, best of 3: 1.14 usec per loop

Case 3. Map Vs List comprehension for function built by lambda
python -mtimeit -s'xs = xrange(10)'  'map(lambda x: x+10,xs)'
1000000 loops, best of 3: 1.29 usec per loop
python -mtimeit -s'xs = xrange(10)'  '[lambda x: x+10 for x in xs]'
1000000 loops, best of 3: 0.958 usec per loop


Time taken by map function is lesser in Case1&2, whereas higher in Case3

                                                        Map                     ListComprehension

1. User defined function                  1.3 usec                      1.39 usec

2. Inbuilt function                           0.926 usec                  1.14 usec   

3. function built by lambda            1.29 usec                    0.958 usec

No comments:

Post a Comment