Skip to content

Extra allocations associated with unused ArgumentError #37639

@BioTurboNick

Description

@BioTurboNick

I've encountered a weird bug causing additional memory to be allocated when running a method that never executes the changed branch.

In 1.5.2-pre.29 and earlier, both functions have 1 allocation. In the current master, the top function has 1 additional allocation.

function hvncat1(dims::Tuple{Vararg{Int, N}}, xs::T...) where T <:Number where N
    a = Array{Int,N}(undef, dims...)
    if prod(dims) != length(xs)
        throw(ArgumentError("argument count does not match specified shape (expected $(prod(dims)), got $(length(xs)))"))
    end

    nr = dims[1]
    nc = dims[2]
    k = 1
    na = prod(dims[3:N])
    @inbounds for d=1:na
        for i=1:nr
            for j=1:nc
                a[i+nr*(j-1)+nr*nc*(d-1)] = xs[k]
                k += 1
            end
        end
    end
    a
end

function hvncat2(dims::Tuple{Vararg{Int, N}}, xs::T...) where T <:Number where N
    a = Array{Int,N}(undef, dims...)
    size1 = prod(dims)
    size2 = length(xs)
    if size1 != size2
        throw(ArgumentError("argument count does not match specified shape (expected $(size1), got $(size2)))"))
    end

    nr = dims[1]
    nc = dims[2]
    k = 1
    na = prod(dims[3:N])
    @inbounds for d=1:na
        for i=1:nr
            for j=1:nc
                a[i+nr*(j-1)+nr*nc*(d-1)] = xs[k]
                k += 1
            end
        end
    end
    a
end

using BenchmarkTools
@btime hvncat1((2, 2, 2), 1, 3, 2, 3, 3, 5, 4, 6) # 2 allocations: 224 bytes in master; 1 allocation: 144 bytes in 1.5.2
@btime hvncat2((2, 2, 2), 1, 3, 2, 3, 3, 5, 4, 6) # 1 allocation: 144 bytes

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions