In ‘Julia High Performance’ (2nd Ed.), the author gives the following example to explain how to obtain type stability in loops:
function simdsum_fixed(x)
s = zero(eltype(x))
@simd for v in A
s += v
end
return s
end
In a previous example, with different code they simply use zero(x). I’ve therefore tried the same function without eltype() as below (simdsum_fixed_b). They seem to work in the same way.
function simdsum_fixed_b(x)
s = zero(x)
@simd for v in A
s += v
end
return s
end
How is then zero(eltype(x)) different from zero(x)? What is the advantage of using the first over the second?
Thanks in advance.
>Solution :
Use zero(eltype(x)) if x is a container (e.g. a vector) and you want additive identity of its elements. Use zero(x) if you want to get the additive identity of x itself.
Example with vector as here the difference is most clearly visible:
julia> x = [1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> zero(x)
3-element Vector{Int64}:
0
0
0
julia> zero(eltype(x))
0