Why is a=a*100 almost two times faster than a*=100? [duplicate]

17

Following the question about Chaining *= += operators and the good comment of Tom Wojcik ("Why would you assume aaa *= 200 is faster than aaa = aaa * 200 ?"), I tested it in Jupyter notebook:

%%timeit aaa = np.arange(1,101,1)
    aaa*=100

%%timeit aaa = np.arange(1,101,1)
    aaa=aaa*100

And I was surprised because the first test is longer than the second one: 1530ns and 952ns, respectively. Why these values are so different?

Share
Improve this question
13
  • 6
    If you reverse the order here, what are the results? – jarmod Apr 20 at 14:11
  • 3
    This is related to numpy. Doesn't happen with regular ints or floats – Pranav Hosangadi Apr 20 at 14:16
  • 1
    possibly related? stackoverflow.com/questions/16034672/… – python_user Apr 20 at 14:19
  • 4
    Changing the range to be np.arange(1,10001,1) actually reverses the results: aaa*=100 is faster! So the in-place is still faster as the input grows in size. For small arrays, for some reason, creating a new array is more efficient... – Tomerikoo Apr 20 at 14:22
  • 2
    @MaPy I think you missed the point. The one assigning a new array is faster... – Tomerikoo Apr 20 at 14:23

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue