Strange behavior with array calls

Why is getindex(g,x) slower than g[x]?

julia> g = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> f(g,x) = g[x]

julia> @btime f($g,2)
  0.025 ns (0 allocations: 0 bytes)
2

julia> @btime getindex($g,2)
  1.813 ns (0 allocations: 0 bytes)
2

A run time of sub nanosecond almost always mean that there was some compiler optimization that made the whole benchmarking loop get optimized away. Also, locally I get

julia> @btime f($g,2)
  1.542 ns (0 allocations: 0 bytes)
2

julia> @btime getindex($g,2)
  1.541 ns (0 allocations: 0 bytes)
2
1 Like

Could it be that the difference in optimizations between our local computers is due to differences in software installed by the operating system or how Julia was compiled for the OS? Mine is running arch linux

Using a range for me still has a performance difference


julia> @btime f($g,1:3)
  1.812 ns (0 allocations: 0 bytes)
1:3

julia> @btime getindex($g,1:3)
  26.105 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
 1
 2
 3

Interesting, it actually returns a range there, so it optimized array reference out.

Looks like this is an actual bug here

julia> y = [4,5,6];

julia> @btime f($y,1:3)
  2.166 ns (0 allocations: 0 bytes)
1:3

julia> @btime getindex($y,1:3)
  25.259 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
 1
 2
 3

That is the wrong result…

julia> f(y,7)
7

should return an error because 3-element array, but returns the value of index

I get the same results, Windows 10, Julia 1.0.1:

julia> @btime f($g,2)
  1.026 ns (0 allocations: 0 bytes)
2

julia> @btime getindex($g,2)
  1.026 ns (0 allocations: 0 bytes)
2

julia> @btime f($g,1:3)
  27.968 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
 1
 2
 3

julia> @btime getindex($g,1:3)
  27.712 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
 1
 2
 3

julia> @btime f($g,7)
  1.026 ns (0 allocations: 0 bytes)
86067088

julia> @btime getindex($g,7)
  1.026 ns (0 allocations: 0 bytes)
86067088

Figured out, julia-2:1.0.3-2 on arch linux is broken, when I revert to julia-2:1.0.3-1 it’s normal.

Are you sure you didn’t misdefine f in your last REPL session? What commit is julia-2:1.0.3-2 on? Would be good to get to the bottom of this.

Updated again and restarted REPL, guess it was just something quirky that happened in that session…

Now that I look back at the history, I did make this experimental definition for f also in the same session

f(x::Vector{M},m=M) where M = m

That’s why f had 3 methods defined for it, and is the cause for the strange behavior.

Please feel free to delete this entire thread if you want to.