JuliaArrays / JuliaArrays/StaticArrays.jl

inconsistent MArray allocation behavior with @inbounds, loop order

Open
#874 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Julia
Stars
844
Forks
159
Avg merge
3d 21h
Merged PRs (30d)
3

Description

Allocations for MArray in an accumulation loop are inconsistent (depend on @inbounds and loop order)

function accum1(L, ::Val{N}) where {N}
    acc = zero(MVector{N,Float64})
    for i ∈ 1:L
        for n ∈ 1:N
            acc[n] += n
        end
    end
    sum(acc) # no allocs if sum(acc) is removed
end

function accum2(L, ::Val{N}) where {N}
    acc = zero(MVector{N,Float64})
    for i ∈ 1:L
        @inbounds for n ∈ 1:N
            acc[n] += n
        end
    end
    sum(acc)
end

function accum3(L, ::Val{N}) where {N}
    acc = zero(MVector{N,Float64})
    for n ∈ 1:N # switch loop order - slower, but no allocs
        for i ∈ 1:L
            acc[n] += n
        end
    end
    sum(acc)
end

@btime accum1($10,$(Val(4)))   #  21.393 ns (1 allocation: 48 bytes)
@btime accum2($10,$(Val(4)))  #  7.710 ns (0 allocations: 0 bytes)
@btime accum3($10,$(Val(4)))  #  21.731 ns (0 allocations: 0 bytes)

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the allocation measurements for accum1, accum2, and accum3 with the supplied Julia examples, comparing the effects of @inbounds and loop order. Trace the StaticArrays MArray behavior involved in zero, indexing, and sum; done means explaining the inconsistent allocation and establishing a consistent result without changing the intended accumulation behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
julia
Domain
performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.