Skip to content

Vector prepend! allocates when there's capacity #59948

@dpinol

Description

@dpinol

#59717 fixed prepend! for small vectors, but the problem still persists in some cases:

1) First insertion allocates in Vector's with capacity 3 or smaller

using Test
function tinyVectorAlwaysAllocates()
    sut = Vector{Int}(undef, 3)
    empty!(sut)

    @test (@allocations(insert!(sut, 1, 1))) == 0
    @test length(sut.ref.mem) == 3
end
tinyVectorAlwaysAllocates()
Test Failed at REPL[11]:5
  Expression: #= REPL[11]:5 =# @allocations(insert!(sut, 1, 1)) == 0
   Evaluated: 1 == 0

2) Fourth insertion allocates in Vectorwith capacity 5

using Test
function fourthInsertReallocates()
    sut = Vector{Int}(undef, 5)
    empty!(sut)

    for i in 1:4
        @test (@allocations(insert!(sut, 1, i))) == 0
    end
    @test length(sut.ref.mem) == 5
end
fourthInsertReallocates()
Test Failed at REPL[8]:6
  Expression: #= REPL[8]:6 =# @allocations(insert!(sut, 1, i)) == 0
   Evaluated: 1 == 0

3) Suggestion for test

In https://github.com/JuliaLang/julia/blob/master/test/arrayops.jl#L533 I suggest checking the lack of allocations with @test (@allocations(insert!(sut, 1, 1))) == 0 instead of with @test length(v.ref.mem) == 5, since the test as it is would fail to detect the allocation if capacity was 3 instead of 5.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions