Skip to content
Julia

Parametric Types & Performance

Define generic, type-stable containers that compile to specialized code.

By EZ4Code Team
typesperformancegenerics

Code

# 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)

Explanation

Parametric types let Vec{Float64,3} and Vec{Int,3} be distinct, fully-typed objects — the JIT generates separate native code for each instantiation, so a Vec{Float64,3} is just three doubles in registers with no boxing. The most common performance bug is type instability (a function returning different types on different branches); @code_warntype highlights any Union return in red, indicating a heap allocation.

More Julia Snippets