@@ -481,6 +481,65 @@ c = (b + 1.0f0)::Complex{T}
481481does not hinder performance (but does not help either) since the compiler can determine the type of ` c `
482482at the time ` k ` is compiled.
483483
484+ ### Be aware of when Julia avoids specializing
485+
486+ As a heuristic, Julia avoids automatically specializing on argument type parameters in three
487+ specific cases: ` Type ` , ` Function ` , and ` Vararg ` . Julia will always specialize when the argument is
488+ used within the method, but not if the argument is just passed through to another function. This
489+ usually has no performance impact at runtime and
490+ [ improves compiler performance] (@ref compiler-efficiency-issues). If you find it does have a
491+ performance impact at runtime in your case, you can trigger specialization by adding a type
492+ parameter to the method declaration. Here are some examples:
493+
494+ This will not specialize:
495+
496+ ``` julia
497+ function f_type (t) # or t::Type
498+ x = ones (t, 10 )
499+ return sum (map (sin, x))
500+ end
501+ ```
502+
503+ but this will:
504+
505+ ``` julia
506+ function g_type (t:: Type{T} ) where T
507+ x = ones (T, 10 )
508+ return sum (map (sin, x))
509+ end
510+ ```
511+
512+ These will not specialize:
513+
514+ ``` julia
515+ f_func (f, num) = ntuple (f, div (num, 2 ))
516+ g_func (g:: Function , num) = ntuple (g, div (num, 2 ))
517+ ```
518+
519+ but this will:
520+
521+ ``` julia
522+ h_func (h:: H , num) where {H} = ntuple (h, div (num, 2 ))
523+ ```
524+
525+ This will not specialize:
526+
527+ ``` julia
528+ f_vararg (x:: Int... ) = tuple (x... )
529+ ```
530+
531+ but this will:
532+
533+ ``` julia
534+ g_vararg (x:: Vararg{Int, N} ) where {N} = tuple (x... )
535+ ```
536+
537+ Note that [ ` @code_typed ` ] ( @ref ) and friends will always show you specialized code, even if Julia
538+ would not normally specialize that method call. You need to check the
539+ [ method internals] (@ref ast-lowered-method) if you want to see whether specializations are generated
540+ when argument types are changed, i.e., if ` (@which f(...)).specializations ` contains specializations
541+ for the argument in question.
542+
484543## Break functions into multiple definitions
485544
486545Writing a function as many small definitions allows the compiler to directly call the most applicable
0 commit comments