Manually forcing some micro-optimisations here MIGHT help you out.
Firstly, mesh.triangles
is a property, with its own getter and setter. You're going to get a slight performance hit there every loop. So let's store that address as a local variable before the loop even starts.
Secondly, the value of mesh.triangles.Length
is always the same. So let's store that in a local variable, instead of calling the property every loop.
Following on from that, your code uses vertices [ ]
while your question refers to mesh.vertices [ ]
. If you're checking mesh.vertices [ ]
every loops, you'll want to locally store that as well.
Now, depending on the compiler, the following micro-optimisations may already have been taken care of. So, you'll have to use your timing technique to verify if this was worthwhile. Having said that, let's now look at the code:
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;
}
As a side note, and while it doesn't help you right now, C#7.x introduces ref struct
and a few other helpful features that'll speed up access, keeping everything on the stack. This article is an interesting read and will be useful when Unity catches up.
Edit : If your mesh doesn't change (which is probably likely), you could then predefine an array of the exact vertices you need. You also then just have to increment a single variable. This is an extreme micro-optimisation. This might help with CPU pre-fetching... (insert shrugging emoji here).
// 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++ ];
}
}