S
S
Stan Jones2018-08-14 14:05:33
Python
Stan Jones, 2018-08-14 14:05:33

Why are combined instructions faster than traditional ones?

One point from Mark Lutz's book - "Learning Python" is just not clear:
The left side of the instruction should be received only once. In a statement, with <> X can be a complex expression that, in combined form, must be evaluated only once. In the longer form <>, X appears twice, and so the expression must be evaluated twice. As a result, combined assignment instructions are usually faster.
I don't understand this point.
Thanks in advance for your explanations.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-08-14
@deliro

With this entry, there is no difference:

In [1]: x = 5

In [2]: 2 < x < 6
Out[2]: True

In [3]: x > 2 and x < 6
Out[3]: True

In [4]: %timeit 2 < x < 6
79.2 ns ± 0.301 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [5]: %timeit x > 2 and x < 6
80 ns ± 0.429 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

and if x is a function (like 2 < x() < 6), then of course in the combined notation the function will be executed only once versus 2 < x() and 6 > x() where it will be executed twice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question