Are the expressions Vector{Type}()
and Type[]
for initializing an empty vector of Type
s completely equivalent in Julia? Is either syntax preferred?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With