Custom Array Performance Issues

Hello, I have the following example of a custom array and I do not know why there is a nearly factor 2 overhead in the performance for my custom array type MyArray

using BenchmarkTools

struct MyArray{T,N} <: AbstractArray{T,N} 
	A::Array{T,N}
end

Base.size(A::MyArray) = size(A.A)
Base.getindex(A::MyArray, i::Int) = getindex(A.A, i)
Base.setindex!(A::MyArray, v, i::Int) = setindex!(A.A, v, i)
Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()

A = rand(1000, 1000)
B = MyArray(rand(1000, 1000))

@btime sum(A)
@btime sum(B)

This results in

  1.368 ms (1 allocation: 16 bytes)
  2.016 ms (1 allocation: 16 bytes)

Could someone help me to find the bottleneck?

Try

Base.@propagate_inbounds Base.getindex(A::MyArray, i::Int) = getindex(A.A, i)

See
https://docs.julialang.org/en/v1/devdocs/boundscheck/#Propagating-inbounds-1

1 Like

This was exactly the missing part. Now the time is the same. Considering how often one simply wraps an array to have a dispatch on custom types, maybe there should be a note on this in the Interface documentation…

Possibly. Can you make a pull request to the docs?

Would be my first time but I could try :wink:

1 Like

see https://github.com/JuliaLang/julia/blob/master/CONTRIBUTING.md#improving-documentation got get started.

Matt’s talk about array implementations from JuliaCon 2018 might also interest you: https://www.youtube.com/watch?v=jS9eouMJf_Y

1 Like

Thanks :wink: I even was there but it has been a while so I probably forgotten everything…

Here is the PR https://github.com/JuliaLang/julia/pull/33420

1 Like