5 ms·
This is easily testable: julia> using BenchmarkTools using OffsetArrays A = rand(1000) O = OffsetArray(A, 0:999)
by 3JPLW 9y ago
This is easily testable:
julia> using BenchmarkTools
using OffsetArrays
A = rand(1000)
O = OffsetArray(A, 0:999)
function naive_sum(A)
s = zero(eltype(A))
@unsafe for i in eachindex(A) # @unsafe will eventually be folded into @inbounds
s += A[i]
end
return s
end
naive_sum (generic function with 1 method)
julia> @btime naive_sum($A)
1.025 μs (0 allocations: 0 bytes)
514.0960505118594
julia> @btime naive_sum($O)
1.023 μs (0 allocations: 0 bytes)
514.0960505118594
Yes, there's an extra operation or two in there, but it's effectively free on modern CPUs due to caching/op latencies/pipelining/etc.
- StefanKarpinski 9y agoThe performance is the same because the core loop in both cases is identical: loop: vaddsd (%rcx), %xmm0, %xmm0 addq $8, %rcx addq $-1, %rax jne loop There's more setup required for offset arrays, but otherwise there's no difference. I'm not sure why arrays having an offset would be any more work: array indexing in general involves adding an index to a base pointer; having an offset effectively just changes what the base pointer value is.