Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two equivalent ways to initialize an empty vector in Julia

Are the expressions Vector{Type}() and Type[] for initializing an empty vector of Types completely equivalent in Julia? Is either syntax preferred?

like image 497
tparker Avatar asked Jan 29 '23 15:01

tparker


1 Answers

Yes, they are effectively identical:

julia> @code_typed Vector{Any}()
CodeInfo(:(begin
        return $(Expr(:foreigncall, :(:jl_alloc_array_1d), Array{Any,1}, svec(Any, Int64), Array{Any,1}, 0, 0, 0))
    end))=>Array{Any,1}

julia> @code_typed Any[]
CodeInfo(:(begin
        return $(Expr(:foreigncall, :(:jl_alloc_array_1d), Array{Any,1}, svec(Any, Int64), Array{Any,1}, 0, 0, 0))
    end))=>Array{Any,1}

The Type[] syntax is actually just like all other x[] syntaxes — it expands to getindex(Type). And there you'll see that it's defined in terms of the Array constructor. It's just a convenient shorthand. I'm not aware of any style guides that prefer one over the other.

like image 143
mbauman Avatar answered Feb 05 '23 15:02

mbauman