并行化 List<T> 上的 Sort() 函数,用于 Unity。

huangapple go评论71阅读模式
英文:

Parallelize the Sort() function for List<T> on Unity

问题

我试图通过并行化某些代码来提高游戏性能。我有一个与这个排序函数相关的性能瓶颈:

_list.Sort((obj1, obj2) => obj1.Distance.CompareTo(obj2.Distance));

变量 _list 是一个 List<Object>

有办法并行化这个吗?

更多信息: Distance 是一个 float,通过 Vector3.Distance() 计算的。它存储在一个私有字段中。它不会每次读取时重新计算。我需要对整个列表进行排序,而不仅仅是部分列表。列表中最多包含 1000/1500 个对象。根据我所做的测试,在最坏的情况下,从分析器中深入分析看到,它需要花费 7 到 10 毫秒的时间。在最坏的情况下,列表是完全未排序的,这是我无法控制的。

英文:

I am trying to improve the performances of a game by parallelizing some code. One of the bottlenecks I have regards this sorting function:

_list.Sort((obj1, obj2) =&gt; obj1.Distance.CompareTo(obj2.Distance));

The variable _list is a List&lt;Object&gt;.

There is a way to parallelize this?

More information: Distance is a float, computed as Vector3.Distance(). It is backed in a private field. It's not computed every time it is read. I need to sort all the list, not only a part of it. The list contains at maximum 1000/1500 objects. In the worst case, from the tests I did, takes between 7 and 10 ms (from what I can see looking in the profiler using the deep profile). The list in the worst case is completely unsorted, is not something I can control.

答案1

得分: 1

使用 AsParallel() 方法进行处理:

_list = _list.AsParallel().OrderBy(x => x.Distance).ToList();

这个方法内部使用快速排序,不太适合并行处理。

Hugo 提供的示例:https://dotnetfiddle.net/qbmZ1y

英文:

approach with AsParallel()

_list = _list.AsParallel().OrderBy(x =&gt; x.Distance).ToList();

this uses internaly quick sort which doesn't scale that good at parallelizing.

Sample by Hugo: https://dotnetfiddle.net/qbmZ1y

huangapple
  • 本文由 发表于 2023年2月27日 16:05:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578029.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定