Does Python optimize lambda x: x -


so wrote code max/min assumes bottleneck on generating data (else i'd use max , min), , takes key function, if not given uses identity function:

if key none:     key = lambda x: x 

and later:

for in iterable:     key_i = key(i) 

and since bottleneck on generator, question might moot, if there's no key, call lambda x: x every item. i assume python optimize identity function away. can tell me if does? or if doesn't, how expensive it? there way better without doubling line count (e.g. ternary operators)?

good question ! optimizer see foo might identity function under predictable conditions , create alternative path replace it's invocation it's known result

let's see opcodes :

>>> def foo(n): ...     f = lambda x:x ...     return f(n) ...  >>> import dis >>> dis.dis(foo)   2           0 load_const               1 (<code object <lambda> @ 0x7f177ade7608, file "<stdin>", line 2>)                3 make_function            0                6 store_fast               1 (f)     3           9 load_fast                1 (f)               12 load_fast                0 (n)               15 call_function            1               18 return_value          

cpython (2.7 , 3.3 tested) not seem optimize out lambda call. perhaps implementation ?

>>> dis.dis(lambda x:x)   1           0 load_fast                0 (x)                3 return_value    

the identity function doesn't much. have 2 load_fast, 1 call_function, , 1 return_value optimize out every time call identity function, versus creation of reliable alternative path (which might more complicated appears interpreter @viraptor says).

maybe else path in python code better.

the real optimization did on min/max example reduce number of invocations of function storing it's result. it's called n times instead of n*4, , thats fair gain !


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -