Difference between += and .+=

What is the difference between the += and the .+= operator in julia when adding two arrays, eg. x = [1,2,3]; y = [4,5,6] x+=y vs x.+=y?

. make it element wise

Specifically, x += y is x = x + y which will allocate a new vector for x+y and assign that to x. x .+= y is x .= x .+ y which won’t allocate a vector, and will modify x.


The answer you got are already true and describe the problem enough, I’ll just add something : You might encounter cases where the += operator is not overloaded for the type you are considering, while the .+= statement basically does a loop and only requires the objects to be iterable (and their iterates to be summable, of course).

This is why I recommend using .+= when possible. There is also the benefit of loop fusion (see the docs). Anyway, the best way (the fastest and easiest for the compiler to understand) is always to write the loop yourself.

You can not actually do this, a += b is just another way of typing a = a + b, not a standalone operator, as mentioned above.

1 Like

Yes, i meant that the + operator might not be overloaded, while the .+ one is available to all iterables.