Reputation: 1636
What is the best approach between the code below where verticesInnerSides.Length / 2
is written in it's complete form each time :
for (int i = 0; i < verticesRoof.Length; i++) {
verticesInnerSides[i * NB_VERTICES + verticesInnerSides.Length / 2] = startInside;
verticesInnerSides[i * NB_VERTICES + verticesInnerSides.Length / 2 + 1] = startInside + Vector3.up * HEIGHT_ROOF;
verticesInnerSides[i * NB_VERTICES + verticesInnerSides.Length / 2 + 2] = endInside;
verticesInnerSides[i * NB_VERTICES + verticesInnerSides.Length / 2 + 3] = endInside + Vector3.up * HEIGHT_ROOF;
}
Or the following where it's written outside the loop once :
myCalculatedVar = verticesInnerSides.Length / 2;
for (int i = 0; i < verticesRoof.Length; i++) {
verticesInnerSides[i * NB_VERTICES + myCalculatedVar] = startInside;
verticesInnerSides[i * NB_VERTICES + myCalculatedVar + 1] = startInside + Vector3.up * HEIGHT_ROOF;
verticesInnerSides[i * NB_VERTICES + myCalculatedVar + 2] = endInside;
verticesInnerSides[i * NB_VERTICES + myCalculatedVar + 3] = endInside + Vector3.up * HEIGHT_ROOF;
}
Will C# compiler optimize this operation in the first case ?
Upvotes: 1
Views: 152
Reputation: 4501
In my opinion the best way to reach readability and performance is:
myCalculatedVar = verticesInnerSides.Length / 2;
for (int i = 0; i < verticesRoof.Length; i++) {
int ind = i * NB_VERTICES + myCalculatedVar;
verticesInnerSides[ind] = startInside;
verticesInnerSides[ind + 1] = startInside + Vector3.up * HEIGHT_ROOF;
verticesInnerSides[ind + 2] = endInside;
verticesInnerSides[ind + 3] = endInside + Vector3.up * HEIGHT_ROOF;
}
But you can waste your time and write some benchmarks test for testing this piece. I am sure that if a bottleneck will exist it will be in another place in the code.
Upvotes: 1
Reputation: 11773
Why would you do it like the first code example to begin with ? The second one (without looking at the compiler) seems more efficient.
As per Code Complete, and many other suggestions: Don't optimize if you don't need to.
If you need to, simply benchmark. (There's plenty of threads, blogs and answers about what to look out for when benchmarking, but I'm sure you'll be able to find them :)
As an extra bonus, here's another answer with all the links you'll need :)
Upvotes: 1