Parametric Types & Performance
Define generic, type-stable containers that compile to specialized code.
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
Broadcasting & Vectorization
Apply a function element-wise over arrays with dot syntax and @.
Multiple Dispatch
Select methods by the runtime types of all arguments, not just the receiver.
Macros & Expressions
Manipulate Julia syntax trees as first-class data via :expr and macro.
Multi-threading & Distributed Compute
Parallelize loops with @threads and offload tasks with @spawn / pmap.
DataFrame Operations (DataFrames.jl)
Filter, transform, group, and join tabular data with DataFrames.jl.
Performance Tips: @inbounds, @fastmath, views
Write Julia that runs at C speed by removing bounds checks, avoiding allocations, and using views.