colinfang
colinfang

Reputation: 21727

Why are there 2 methods for getindex?

In the source code, I see 2 methods are implemented for getindex.

# T[x...] constructs Array{T,1}
function getindex(T::Type, vals...)
    a = Array(T,length(vals))
    @inbounds for i = 1:length(vals)
        a[i] = vals[i]
    end
    return a
end

function getindex(::Type{Any}, vals::ANY...)
    a = Array(Any,length(vals))
    @inbounds for i = 1:length(vals)
        a[i] = vals[i]
    end
    return a
end

Why is the second one required? I have read the performance-tips, but in this case type of a is stable: always T.

Upvotes: 1

Views: 119

Answers (1)

Toivo Henningsson
Toivo Henningsson

Reputation: 2699

These are both getindex methods that are used for creating arrays through syntax such as e.g.

Int[1,4,9]

(first method) and

Any[1,4.0,"9"]

(second method). The second one is not strictly required, but is an optimization to cut down on compiler time and resources.

The type signature ::ANY (as opposed to ::Any) instructs the compiler not to specialize on the actual types of those arguments, which makes sense in this case since there would be no performance gain. It makes sense to have this special case in place since arrays will likely be constructed with the Any[...] syntax using a wide range of type combinations.

Upvotes: 3

Related Questions