In a simple case, such as
v = collect(1:10)
sqrs = similar(v)
map!(abs2, sqrs, v)
would it be better to use broadcast!
? I am using the !
form (instead of a .=
assignment) because this expression could be part of a larger expression. My guess is that broadcast!
could be preferred if there was a chance that it could be fused with other operations.
I would agree with your guess.
My understanding is that broadcast
is for AbstractArray
s and that map
is for general collections. So, roughly speaking, if your collection has a well-defined order, use broadcast
. In other cases (e.g. Set
or Dict
), use map
.
So, in your case I would agree: broadcast
.
map!
and broadcast!
are indeed basically the same for these one-argument cases. They only way you’ll see a difference is if a type specifically specialized one but not the other — and then it can only ever be a difference in performance. Broadcasting does have the big advantage of fusion.
You’re more likely to see a difference between the non-bang map
and broadcast
since they have a very different system of allocating the resulting array: the former uses similar
for AbstractArray
s whereas the latter uses broadcast styles.
1 Like