user14603676
user14603676

Reputation:

is calling a variable more expensive than calling a function in another function's paramters?

I have a functions for example like this


def first(x):
    return x * 2


def second(x):
    return x / 2

would be

a = first(2)
b = second(a)

more expensive because of that creating of variable a and checking type and calling it by python when using it, than doing something like this?


b = second(first(2))

Upvotes: 1

Views: 584

Answers (1)

abc
abc

Reputation: 11929

You can check the bytecode generated by using the dis module.

>>> dis.dis("b=second(first(2))")
  1           0 LOAD_NAME                0 (second)
              2 LOAD_NAME                1 (first)
              4 LOAD_CONST               0 (2)
              6 CALL_FUNCTION            1
              8 CALL_FUNCTION            1
             10 STORE_NAME               2 (b)
             12 LOAD_CONST               1 (None)
             14 RETURN_VALUE

>>> dis.dis("a=first(2); b=second(a)")
  1           0 LOAD_NAME                0 (first)
              2 LOAD_CONST               0 (2)
              4 CALL_FUNCTION            1
              6 STORE_NAME               1 (a)
              8 LOAD_NAME                2 (second)
             10 LOAD_NAME                1 (a)
             12 CALL_FUNCTION            1
             14 STORE_NAME               3 (b)
             16 LOAD_CONST               1 (None)
             18 RETURN_VALUE

The first case introduces 2 additional operations: a store and a load for a.

              6 STORE_NAME               1 (a)
             10 LOAD_NAME                1 (a)

However, there will be no noticeable difference in the runtime, and the first solution is always better for readability and debug.

Upvotes: 3

Related Questions