# Multiple Dispatch + JIT (or Dynamic and Compiled)

When people ask me why I use Julia, my immediate response is “multiple dispatch”. Julia is well-known for its performance, but performance is only a part of what keeps me using it every day. Multiple dispatch is a feature where different code is called by a function depending on the types of the arguments. Combined with the JIT (Just-in-time compiler), Julia will automatically compile specialized code, depending on the types of the arguments you give it.

## Simple Example

f(x) = x + x


I haven’t told Julia anything about what x is, but as long as it’s a type that supports addition, Julia will compile an optimized method for it. You can peek at the LLVM compiler code with the @code_llvm macro.

julia> @code_llvm f(1)

define i64 @julia_f_62945(i64) #0 !dbg !5 {
top:
%1 = shl i64 %0, 1
ret i64 %1
}

julia> @code_llvm f(1.0)

define double @julia_f_62949(double) #0 !dbg !5 {
top:
%1 = fadd double %0, %0
ret double %1
}


Ignoring some of the details, notice that one method is specific to 64-bit integers and the other for double precision floats.

## What About More Complicated Types?

Here I’m using the Distributions package to implement a naive quantile finder using Newton’s Method.

using Distributions

function myquantile(d, q)
out = mean(d)
for i in 1:10
out -= (cdf(d, out) - q) / pdf(d, out)
end
out
end


Again, I have not told Julia anything about what d or q is, but when I provide arguments such as Distributions.Normal(0, 1) and 0.5, Julia will compile specialized code to run the algorithm and then return the median for a standard normal distribution (which is 0).

julia> myquantile(Normal(0,1), .5)
0.0


Right out of the box, myquantile will also work with other distributions/quantiles.

julia> myquantile(Gamma(5,1), .7)
5.890361313697006

julia> myquantile(Beta(2, 4), .1)
0.11223495854585855


If I were to implement this quantile algorithm in R, I would need to rewrite it for each distribution using the dnorm/pnorm family of functions.

## Conclusion

Multiple dispatch is now invaluable to my daily programming life, and with Julia, you don’t need to sacrifice performance for it.

Come for the speed. Stay for the productivity.