1

I have two lists :

x = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
y = ['a','b','c','d','e','f','g','h','i','j']

I am merging these lists to get a dictionary like this :

z = {97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g', 104: 'h', 105: 'i', 106: 'j'}

I am completing this task with the help of map function.

It can be done in two ways :

first way :

z = map(lambda a,b : (a+97 , b), x, y)

second way :

def fun(a,b): return (a+97, b)
z = dict(map(fun, x, y))

ANALYSIS :

import timeit

min(timeit.repeat(lambda:dict(map(lambda a,b:(a+97,b),x,y))))

def fun(a,b):
    return (a+97, b)

min(timeit.repeat(lambda:dict(map(fun, x, y))))

Above code is giving me the following output :

8.535995744000047

8.080758586999991

This code have a time difference of 0.45523715700005596 ms. I have been informed that lambda expressions are same like inline functions those are used to increase the performance(execution speed).

But according to above result it seems like this thought is a myth. Is there any specific reason behind these weird time tests? Are local functions with same content are faster then lambda expressions?

I know the third way also to complete above task i.e.

z = dict([(k+97 , v) for k,v in zip(x, y)])

with 7.950903342999936 ms,

But I am more interested in above test results.

Community
  • 1
  • 1
Er. Harsh Rathore
  • 758
  • 1
  • 7
  • 21
  • Doesn't answer question, but I get pretty identical times for both @ ~4.6 us/loop-----%%timeit z = dict(map(lambda a,b : (a+97 , b), x, y))=>100000 loops, best of 3: 4.64 µs per loop vs. %%timeit def fun(a,b): return (a+97, b) z = dict(map(fun, x, y))=>100000 loops, best of 3: 4.69 µs per loop – DarrylG Oct 07 '19 at 02:50
  • @DarrylG you are right it is a micro difference, but it is in wrong direction yet. – Er. Harsh Rathore Oct 07 '19 at 02:58

1 Answers1

0

Using min is a terrible measure of performance as execution speed of any program is affected by other processes running on the machine. An average over a significant sample is far more informative

Why the lambda is slower

You are re-defining the lambda function on every iteration of timeit, if you were to assign the lambda to a variable and use it you would see that there is no significant difference

foo = lambda a, b: (a + 97, b)
min(timeit.repeat(lambda:dict(map(foo, x, y))))
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50