c# - 访问网格顶点性能问题
问题描述
我遇到此代码运行缓慢的问题(执行循环大约需要 250 毫秒)
mesh.triangles.Length 是 8700。
我在最新的 Unity 平台(版本 2018.2.3)上使用 c#。
我怀疑这是因为我在每次迭代的两个数组之间切换,即。我从三角形中取一个值,然后查找它的顶点元素。
mesh.triangles 是一个整数数组。mesh.vertices 是 Vector3 的数组。
while (j < mesh.triangles.Length)
{
m_Particles [currentParticlePos].position = vertices[mesh.triangles[j]];
// allocate a particle to every 3rd vertex position.
j = j + 3;
currentParticlePos++;
}
解决方案
在此处手动强制进行一些微优化可能会帮助您。
首先,mesh.triangles
是一个属性,有自己的 getter 和 setter。你会在每个循环中获得轻微的性能影响。因此,让我们在循环开始之前将该地址存储为局部变量。
其次, 的值mesh.triangles.Length
始终相同。所以让我们将它存储在一个局部变量中,而不是在每个循环中调用该属性。
从那以后,您的代码使用vertices [ ]
,而您的问题是指mesh.vertices [ ]
. 如果您要检查mesh.vertices [ ]
每个循环,您也需要在本地存储它。
现在,根据编译器的不同,可能已经处理了以下微优化。因此,您必须使用计时技术来验证这是否值得。说了这么多,现在让我们看一下代码:
int [ ] triangles = mesh.triangles;
int length= triangles.Length;
int [ ] vertices = mesh.vertices;
while (j < length)
{
m_Particles [ currentParticlePos++ ].position = vertices [ triangles [ j ] ];
// allocate a particle to every 3rd vertex position.
j = j + 3;
}
附带说明一下,虽然它现在对您没有帮助,但 C#7.x 引入ref struct
了一些其他有用的功能,这些功能将加快访问速度,将所有内容保留在堆栈中。这篇文章很有趣,当 Unity 赶上来时会很有用。
编辑:如果您的网格没有改变(这很可能),那么您可以预定义您需要的确切顶点的数组。然后你也只需要增加一个变量。这是一个极端的微观优化。这可能有助于 CPU 预取...(在此处插入耸肩表情符号)。
// The mesh. Assigned as you see fit.
Mesh mesh;
// The length of the new vertices array, holding every third vertex of a triangle.
int length = 0;
// The new vertices array holding every third vertex.
Vector3 [ ] vertices;
void Start ( )
{
int [ ] triangles = mesh.triangles;
length = triangles.Length / 3;
vertices = new Vector3 [ length ];
for ( int count = 0; count < length; count++ )
vertices [ count ] = mesh.vertices [ triangles [ count * 3 ] ] ;
}
private void Update ( )
{
int j = 0;
while ( j < length )
{
m_Particles [ j ].position = vertices [ j++ ];
}
}
推荐阅读
- java - 我的代码有错误,我正在尝试为未来的项目测试一些东西,但它一直无法正常工作
- c++ - 如果变量数据包含的整数大于向量的所有元素,则仅在 Visual Studio 上接收“向量下标超出范围”?
- excel - 工作表更改事件的问题
- javascript - fullcalendar.js 插件上的单击事件不起作用
- python - 如何在 Instagram 上获得帖子描述?
- javascript - Mongoose .findByIdAndUpdate() 控制台记录返回但无法分配给属性
- php - 如何为 public_html 文件路径编写 htaccess 代码?
- javascript - 使用多个选择下拉列表过滤 HTML 表格
- javascript - Mongoose:过滤嵌套文档
- function - 在 for 循环中使用 value_counts 创建函数