Should I use broadcasting or write the function directly for higher dimensional input?

Let’s say I have a 1000×3 Matrix{Int64}. I want to loop over each row and execute some function that doesn’t return anything.
My intuitive approach was to write a function that takes a 3-element vector and later broadcast that function using mapslices.

But I think I might be a bit tunneling on this broadcasting thing.

Would it be less performant to write a for-loop that does the same thing and loops over every row?
Or are there other best practices to loop over an input?

Would it be a different approach, if I want to actually map my input data?

No, it would probably be more performant to write a for loop, because broadcasting (or map) allocates an array for the result. If you don’t want to return anything, presumably you are doing something else, e.g. summing or something?

Loops are fast in Julia (if they are written properly). There’s nothing magical about broadcast operations except for the compact syntax — under the hood, they are implemented in Julia code with ordinary loops.

Let’s say I have a 1000×3 Matrix{Int64}.

Note that if you are working with a bunch of 3-component vectors, e.g. for 3d coordinates, you should consider using StaticArrays.

Note also that Julia arrays are stored column-major so accessing a 1000x3 array by rows will be less efficient than accessing a 3x1000 array by columns. (Or a length-1000 array of 3-component staticarrays.)


Thank you for the detailed answer!
Yeah makes completely sense, so broadcasting should only be used, if I want to do some manipulations and return the result array? Or would I use a loop there as well?

I will definitely try out StaticArrays, too. And will start to access column wise. :ok_hand: