Skip to content

Commit 1004a7a

Browse files
Mention .+= in response to why += allocates (JuliaLang#42745)
Co-authored-by: Simeon Schaub <[email protected]> Co-authored-by: Simeon Schaub <[email protected]>
1 parent d3ce3fd commit 1004a7a

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

doc/src/manual/faq.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -834,9 +834,10 @@ no values and no subtypes (except itself). You will generally not need to use th
834834

835835
### Why does `x += y` allocate memory when `x` and `y` are arrays?
836836

837-
In Julia, `x += y` gets replaced during parsing by `x = x + y`. For arrays, this has the consequence
837+
In Julia, `x += y` gets replaced during lowering by `x = x + y`. For arrays, this has the consequence
838838
that, rather than storing the result in the same location in memory as `x`, it allocates a new
839-
array to store the result.
839+
array to store the result. If you prefer to mutate `x`, use `x .+= y` to update each element
840+
individually.
840841

841842
While this behavior might surprise some, the choice is deliberate. The main reason is the presence
842843
of immutable objects within Julia, which cannot change their value once created. Indeed, a
@@ -869,8 +870,8 @@ After a call like `x = 5; y = power_by_squaring(x, 4)`, you would get the expect
869870
`x`, after the call you'd have (in general) `y != x`, but for mutable `x` you'd have `y == x`.
870871

871872
Because supporting generic programming is deemed more important than potential performance optimizations
872-
that can be achieved by other means (e.g., using explicit loops), operators like `+=` and `*=`
873-
work by rebinding new values.
873+
that can be achieved by other means (e.g., using broadcasting or explicit loops), operators like `+=` and
874+
`*=` work by rebinding new values.
874875

875876
## [Asynchronous IO and concurrent synchronous writes](@id faq-async-io)
876877

0 commit comments

Comments
 (0)