Picaud Vincent
Picaud Vincent

Reputation: 10982

Unexpected memory allocation in basic for loop?

I am wondering why @btime reports one memory allocation per element in basic loops like these ones:

julia> using BenchmarkTools

julia> v=[1:15;]
15-element Array{Int64,1}:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15

julia> @btime for vi in v end
  1.420 μs (15 allocations: 480 bytes)

julia> @btime for i in eachindex(v) v[i]=-i end
  2.355 μs (15 allocations: 464 bytes)

I do not know how to interpret this result:


julia> versioninfo()
Julia Version 1.5.1
Commit 697e782ab8 (2020-08-25 20:08 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Xeon(R) CPU E5-2603 v3 @ 1.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-9.0.1 (ORCJIT, haswell)

Upvotes: 3

Views: 277

Answers (1)

giordano
giordano

Reputation: 8344

You're benchmarking access to the global variable v, which is the very first performance tip you should be aware of.

With BenchmarkTools you can work around that by interpolating v:

julia> @btime for vi in v end
  555.962 ns (15 allocations: 480 bytes)

julia> @btime for vi in $v end
  1.630 ns (0 allocations: 0 bytes)

But note that in general it's better to put your code in functions. The global scope is just bad for performance:

julia> f(v) = for vi in v end
f (generic function with 1 method)

julia> @btime f(v)
  11.410 ns (0 allocations: 0 bytes)

julia> @btime f($v)
  1.413 ns (0 allocations: 0 bytes)

Upvotes: 4

Related Questions