The style guide says Don’t use unnecessary static parameters but does not explain why.
Is this just a question of style or are there other considerations?
The style guide does explain it:
especially if
T
is not used in the function body. Even ifT
is used, it can be replaced withtypeof(x)
if convenient. There is no performance difference. Note that this is not a general caution against static parameters, just against uses where they are not needed.
There is no performance difference, so is this just a caution against typing to much? I did in fact read the style guide . My question was about an explanation beyond what was in the guide.
In a sense, yes. Newcomers to Julia sometimes assume that the redundant T
in foo(x::T) where {T}
is needed for performance. Generally it isn’t, but note the exceptions.
Yes, there is definitely a difference between foo(x)
and foo(x::T) where {T}
. But to make it clear, is there some subtle difference between foo(x::Real)
and foo(x::T) where {T<:Real}
?
Not from the perspective of Julia’s compiler (again, given the qualifications above, if you don’t otherwise need T
etc).
No. And foo(x)
is implicitly foo(x::Any)
, just replace Any
with Real
and it is the same example, just shorter because Any
is assumed.
There is (or at least used to be) a difference with respect to no-specialize heuristics for higher-order functions: higher(fun::Function, args...)
gives the compiler license to heuristically decide whether to specialize on typeof(fun)
. If you instead write higher(fun::F, args...) where {F<:Function}
, then you force specialization (most of the time the compiler will specialize anyways).
Is this the case? The documentation linked above says that
g_func(g::Function, num) = ntuple(g, div(num, 2))
won’t specialize. Is it a hint rather than a guarantee?
More of a hint. If you don’t want to specialize, use @nospecialize
Yep, if you don’t want to specialize, use @nospecialize
, if you absolutely want to specialize, use the foo(x::T) where T
idiom, and if you trust that the compiler knows best, just write foo(x)
.