Skip to content

Comment on Speedup from switch to +=

Comments

Because of operator overloading "+=" can call a more optimized method than "+". If this code was written in a language without operator overloading I don't think this would be a very interesting pull request. THis could be a example of why some people don't like operator overloading and why some programing languages (java, zig, etc) do not implment the feature.

I don't think this is an operator overloading thing? It's just that `x = y + x` is equivalent to

    z = y + x
    x = z
Basically, creating an object `z` just to throw it away.

`x += y` just adds y to x directly without any intermediary.

You could write this in any language pretty easily. For example, in Rust:

    let x = "abc".to_string();
    let y = "123".to_string();
    let x = x + &y;
as opposed to the more efficient:
    let mut x = "abc".to_string();
    let y = "123".to_string();
    x.push_str(&y);
It's just using an operation to mutate in place vs an immutable operation.
I don't think this is an operator overloading thing?

It’s the confusion / idea that this is trivial change which is the overload thing.

If python did not have operator overloading it would not be used for numeric programming to the extent it is. Overloading is key to its success in that field.

The problem is thinking `+' and `+=' are the same, they are not and `+' should not be used when `+=' can be used.

Operator overloading is a major reason why libraries like pytorch exist so IMO that's a moot point.

Btw there's ongoing work to automatically optimize expressions like this. See the XLA compiler for example. Right now deep learning has a ton of seemingly obvious compute/memory optimisations that are not done automatically.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.