When one has an array of objects it is often desirable (e.g. for performance reasons) to update (replace) some of the objects in place. For example, if you have an array of integers, you might want to replace the negative integers with positive ones:
// Faster for primitives
var i = 0
while (i < a.length) {
if (a(i) < 0) a(i) = -a(i)
i += 1
}
// Fine for objects, often okay for primitives
for (i <- a.indices) if (a(i) < 0) a(i) = -a(i)
What is the canonical way to perform a modification like this using the parallel collections library?
As far as parallel arrays are considered - it's an oversight. A parallel transform
for parallel arrays will probably be included in the next release.
You can, however, do it using a parallel range:
for (i <- (0 until a.length).par) a(i) = computeSomething(i)
Note that not all mutable collections are modifiable in place this way. In general, if you wish to modify something in place, you have to make sure it's properly synchronized. This is not a problem for arrays in this case, since different indices will modify different array elements (and the changes are visible to the caller at the end, since the completion of a parallel operation guarantees that all writes become visible to the caller).
Sequential mutable collections have methods like transform
which work in-place.
Parallel mutable collections lack these methods, but I'm not sure there is a reason behind it or if it is just an oversight.
My answer is that you're currently out of luck, but you could write it yourself of course.
Maybe it would make sense filing a ticket after this has been discussed a bit more?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With