I read that in Julia it’s better to allow more generic type annotation and that type annotation be it done or not does not have an impact on the performance. I think I might have misunderstood what I read. So I did a microbenchmark to see what is going on. I defined four functions in which I annotated the types of the inputs in three and did not annotate the type for the fourth function all doing the same thing. Consider the code below:
using BenchmarkTools
function test_number(x::Vector{Number})
return sum(x)
end
function test_real(x::Vector{Real})
return sum(x)
end
function test_float(x::Vector{Float64})
return sum(x)
end
function test_notype(x)
return sum(x)
end
x_number = ones(Number,100)
x_real = ones(Real,100)
x_float = ones(Float64, 100);
@btime test_number(x_number);
takes 1.590 μs
@btime test_real(x_real);
takes 1.589 μs
@btime test_float(x_float);
takes 22.573 ns
@btime test_notype(x_number);
takes 1.566 μs
@btime test_notype(x_real);
takes 1.548 μs
@btime test_notype(x_float);
takes 45.605 ns
- Why does
test_float
function is fastest among these if type annotation does not impact the performance?
I had the impression thattest_notype
should have been as fast astest_float
since I thought Julia itself “specialize” this function for float input, however, whiletest_notype
is faster thantest_number
andtest_real
, it is not more performant thantest_float
. - Why isn’t
test_notype
as fast astest_float
for float input? - When should I type annotate the function arguments for performance?