Just collecting the answers and comments from other users in a single post:
No, there is nothing faster than a loop in Julia
Unlike other scripting languages like Python and R, loops are fast in Julia. In fact, other "vectorized" operations, like broadcasting, are implemented in terms of Julia loops themselves. Thus, a fast solution could be:
function initialize_vector(range::AbstractRange)
v = Vector{MyStruct}(undef, length(range))
@inbounds for i in eachindex(range)
v[i] = MyStruct(range[i], 0)
end
return v
end
Broadcasting is both fast and convenient
Broadcasting is almost, or sometimes just as fast as looping, and can often be more terse and convenient. In this case, the function initialize_vector
above can be written:
initialize_vector(range::AbstractRange) = MyStruct.(range, 0)
Benchmarking shows that the two functions are almost the same in speed.
Remember to type the fields in your struct for faster code
Julia relies on accurate inference of types to create fast, specialized code. If the types of MyStruct.a
and MyStruct.b
can be anything, it's generally not possible to infer exactly what kind of operations should be performed on a MyStruct
. Even in this case, where the compiler is able to infer that the types are Int
, each MyStruct
has to contain references to heap-allocated Int
s instead of being stack-allocated. Thus, a 10x speedup is obtained from simply changing
struct MyStruct
a
b
end
to
struct MyStruct
a::Int
b::Int
end
If you want to the type of Mystruct.a
and MyStruct.b
to be able to vary, you can create a parametric MyStruct
, like so:
struct MyStruct{T}
a::T
b::T
end