Skip to content

Commit 18cbaba

Browse files
authored
clarify common confusion about allocations (#46383)
1 parent 6f595e6 commit 18cbaba

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

doc/src/manual/performance-tips.md

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,16 +90,23 @@ On the first call (`@time sum_global()`) the function gets compiled. (If you've
9090
in this session, it will also compile functions needed for timing.) You should not take the results
9191
of this run seriously. For the second run, note that in addition to reporting the time, it also
9292
indicated that a significant amount of memory was allocated. We are here just computing a sum over all elements in
93-
a vector of 64-bit floats so there should be no need to allocate memory (at least not on the heap which is what `@time` reports).
93+
a vector of 64-bit floats so there should be no need to allocate (heap) memory.
94+
95+
We should clarify that what `@time` reports is specifically *heap* allocations, which are typically needed for either
96+
mutable objects or for creating/growing variable-sized containers (such as `Array` or `Dict`, strings, or "type-unstable"
97+
objects whose type is only known at runtime). Allocating (or deallocating) such blocks of memory may require an expensive
98+
system call (e.g. via `malloc` in C), and they must be tracked for garbage collection. In contrast, immutable values like
99+
numbers (except bignums), tuples, and immutable `struct`s can be stored much more cheaply, e.g. in stack or CPU-register
100+
memory, so one doesn’t typically worry about the performance cost of "allocating" them.
94101

95102
Unexpected memory allocation is almost always a sign of some problem with your code, usually a
96103
problem with type-stability or creating many small temporary arrays.
97104
Consequently, in addition to the allocation itself, it's very likely
98105
that the code generated for your function is far from optimal. Take such indications seriously
99106
and follow the advice below.
100107

101-
If we instead pass `x` as an argument to the function it no longer allocates memory
102-
(the allocation reported below is due to running the `@time` macro in global scope)
108+
In this particular case, the memory allocation is due to the usage of a type-unstable global variable `x`, so if we instead pass `x` as an argument to the function it no longer allocates memory
109+
(the remaining allocation reported below is due to running the `@time` macro in global scope)
103110
and is significantly faster after the first call:
104111

105112
```jldoctest sumarg; setup = :(using Random; Random.seed!(1234)), filter = r"[0-9\.]+ seconds \(.*?\)"

0 commit comments

Comments
 (0)