If you have both dictionaries created inside the function, then the first will be more efficient - although the first does two calculations when only one is required, the latest version has more overhead for creating a lambda every time it is called
>>> import timeit >>> setup = "from __main__ import convert_to_celsius, convert_to_celsius_lambda, convert_to_celsius_lambda_once" >>> timeit.timeit("convert_to_celsius(100, 'kelvin')", setup=setup) 0.5716437913429102 >>> timeit.timeit("convert_to_celsius_lambda(100, 'kelvin')", setup=setup) 0.6484164544288618
However, if you move the lambda dictionary out , the function:
CONVERSION_DICT = { 'kelvin': lambda x: x - 273.15, 'romer': lambda x: (x - 7.5) * 40 / 21 } def convert_to_celsius_lambda_once(temp, source): return CONVERSION_DICT[source](temp)
then the latter is more efficient, since lambda objects are created only once, and the function performs only the necessary calculations for each call:
>>> timeit.timeit("convert_to_celsius_lambda_once(100, 'kelvin')", setup=setup) 0.3904035060131186
Note that this will only be an advantage when the function is called a lot (in this case, 1,000,000 times), so the overhead of creating two objects of the lambda function is less than the time taken to calculate the two results when only one is needed.
jonrsharpe
source share