Skip to content
Julia

参数化类型与性能

定义泛型、类型稳定的容器,编译为专用代码。

#types#performance#generics

Code

julia
# Parametric struct: the element type T is a type parameter
struct Vec{T, N}
    data::NTuple{N, T}
end

# Concrete instantiations are different types
v1 = Vec{Float64, 3}((1.0, 2.0, 3.0))
v2 = Vec{Int, 3}((1, 2, 3))

# Methods can be written generically and still specialize
Base.:+(a::Vec{T,N}, b::Vec{T,N}) where {T,N} =
    Vec{T,N}(map(+, a.data, b.data))

# Type stability: a function always returns the same type
function unstable(x)
    if x > 0
        return 1.0
    else
        return 0     # Int! Bad — caller gets a boxed Union{Float64,Int}
    end
end

# Stable version:
function stable(x)
    return x > 0 ? 1.0 : 0.0
end

# Inspect type stability with @code_warntype
@code_warntype unstable(2)
@code_warntype stable(2)