When should I use broadcasting in Julia instead of a loop?

I’m still getting used to Julia’s broadcasting syntax, especially the use of . with functions and operators.

For simple cases, something like:

y = sin.(x) .+ 1

is very convenient.

But once the expression gets a little more complicated, I sometimes find an explicit loop easier to read.

So I’m wondering: in normal Julia code, when do you personally prefer broadcasting, and when would you switch to a loop?

Is this mostly a readability choice, or are there performance differences I should keep in mind as well?

I’m mainly trying to build good habits early rather than automatically adding dots everywhere.

I only use broadcasting when its single line if its 2 line I just make the loop to fuse them. I don’t know if its the right thing to do but for micro optim I always endup doing it.

Welcome to the community! Note that you can use @. in this case:

y = @. sin(x) + 1

I love wrapping stuff into functions and then calling them with the dot. It’s very satisfying to do this :slight_smile: