I have a custom OnRenderObject() function that draws wireframe meshes using GL_LINES. After adding bunch of objects to the scene I found that rendering about 10-15k triangles will drop my FPS to 9-10. Finally I managed to find the culprit, below is ‘before’ and ‘after’ code.
before:
Vector3 A, B, C;
A = B = C = Vector3.zero;
GL.PushMatrix ();
GL.MultMatrix (transform.localToWorldMatrix);
GL.Begin (GL.LINES);
GL.Color (Color.white);
for (int fi = 0; fi < currentMesh.triangles.Length; fi += 3) {
byte fi0 = edgeVisibility [fi];
byte fi1 = edgeVisibility [fi+1];
byte fi2 = edgeVisibility [fi+2];
if (fi0 + fi1 + fi2 == 0) continue;
A = currentMesh.vertices [currentMesh.triangles [fi + 0]]; // org A
B = currentMesh.vertices [currentMesh.triangles [fi + 1]]; // org C
C = currentMesh.vertices [currentMesh.triangles [fi + 2]]; // org B
after:
Vector3 A, B, C;
A = B = C = Vector3.zero;
Vector3[] vertices = currentMesh.vertices;
int[] triangles = currentMesh.triangles;
GL.PushMatrix ();
GL.MultMatrix (transform.localToWorldMatrix);
GL.Begin (GL.LINES);
GL.Color (Color.white);
for (int fi = 0; fi < triangles.Length; fi += 3) {
byte fi0 = edgeVisibility [fi];
byte fi1 = edgeVisibility [fi+1];
byte fi2 = edgeVisibility [fi+2];
if (fi0 + fi1 + fi2 == 0) continue;
A = vertices [triangles [fi + 0]]; // org A
B = vertices [triangles [fi + 1]]; // org C
C = vertices [triangles [fi + 2]]; // org B
So why does the second version work significantly faster?
Shouldn’t accessing properties in a loop be optimized by the compiler?