Skip to content

Extending setindex for vector indexing #764

Open
@Micket

Description

@Micket

Learning from my experiments on #745 i looked back at the missing support for vector indexing in setindex.

@inline function setindex(a::SVector{L}, v::AbstractArray, indices::AbstractArray) where L
    out = MVector(a)
    for (i, x) in zip(indices, v)
        # Do boundscheck here to allow Julia to fully elide the dynamic allocation.
        @boundscheck if (i < 1 || i > L)
            throw(BoundsError(a, i))
        end
        @inbounds out[i] = x
    end
    return SVector(out)
end

while we're at it, looks like setindex for scalars can easily be written this way as well.

@inline function setindex2(a::SVector{L}, x, index::Integer) where L
    out = MVector(a)
    # Do boundscheck here to allow Julia to fully elide the dynamic allocation.
    @boundscheck if (index < 1 || index > L)
        throw(BoundsError(a, index))
    end
    @inbounds out[index] = x
    return SVector(out)
end

Looking at assembly, it looks nicer for this implementation. I have had some mixed results trying to benchmark this; peaking at @code_native looked very efficient, but benchmark times still fell a bit short. Perhaps my benchmarks were lacking, or i missed something.

So is this interesting?

Metadata

Metadata

Assignees

No one assigned

    Labels

    arraysAbstractArray interface and array operations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions