I am interested in understanding the actual difference, if any, between the following two function definitions
function foo(n::Integer)
println("hello")
end
function foo{T<:Integer}(n::T)
println("hello")
end
As far as I understand the second form triggers a new compilation every time the function is called for a new type T, but what actually happens in the first case? Is there any effect on performance associated to the first form?
Thanks
Parameters on function arguments are for method disambiguation rather than performance. From the docs http://docs.julialang.org/en/latest/manual/style-guide/#avoid-writing-overly-specific-types
The key thing to realize is that there is no performance penalty to defining only the general addone(x) = x + one(x), because Julia will automatically compile specialized versions as needed. For example, the first time you call addone(12), Julia will automatically compile a specialized addone function for x::Int arguments, with the call to one() replaced by its inlined value 1. Therefore, the first three definitions of addone above are completely redundant.
EDIT to address comment:
The difference between the two signatures is really only apparent when there are more than one argument
Consider the two functions:
julia> function foo(n::Integer, m::Integer)
println(typeof(n), typeof(m))
end
julia> function foo{T<:Integer}(n::T, m::T)
println("Parameterized: ", typeof(n), typeof(m))
end
In the first function n
and m
must both be integers but they do not have to be the same subtype of integer. In the second function, both m
and n
must be the same subtype
julia> foo(1, 2)
Parameterized: Int64Int64
julia> foo(1, Int32(1))
Int64Int32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With