使用并行集合就地转换数组 [英] Transforming arrays in-place with parallel collections

查看:42
本文介绍了使用并行集合就地转换数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个对象有一组对象时,通常需要(例如出于性能原因)更新(替换)一些对象.例如,如果您有一个整数数组,您可能想用正整数替换负整数:

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?

推荐答案

就考虑并行阵列而言 - 这是一个疏忽.并行数组的并行transform 可能会包含在下一个版本中.

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).

这篇关于使用并行集合就地转换数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆