Original Post
I'm trying not to go overboard with micro-optimizations for my engine's math API, but I am trying to put some consideration into performance. For example, it's my understanding than multiplication is slightly faster than division, and saves a few CPU cycles here and there; and this can add up when high-frequency code is executing over and over in a game loop. So I have done things like this example from my Matrix structure:
[source lang="csharp"]
public static Matrix operator /(Matrix mat, float div) {
#if PERFORM_CHECKS
if (div == 0)
throw new MathematicalException(
"Divisor is zero.", new DivideByZeroException());
#endif
float num = 1f / div;
var result = Matrix.Identity;
result.M11 = mat.M11 * num;
result.M12 = mat.M12 * num;
result.M13 = mat.M13 * num;
result.M14 = mat.M14 * num;
result.M21 = mat.M21 * num;
result.M22 = mat.M22 * num;
result.M23 = mat.M23 * num;
result.M24 = mat.M24 * num;
result.M31 = mat.M31 * num;
result.M32 = mat.M32 * num;
result.M33 = mat.M33 * num;
result.M34 = mat.M34 * num;
result.M41 = mat.M41 * num;
result.M42 = mat.M42 * num;
result.M43 = mat.M43 * num;
result.M44 = mat.M44 * num;
return result;
}[/source]
Is this correct/true, and should I be doing it this way? And what other optimizations might I use in general to make my math code blazing fast and efficient?
Might I even consider doing something like this:
[source lang="csharp"]#if !PERFORM_CHECKS
unchecked {
#endif
// math code here...
#if !PERFORM_CHECKS
}
#endif[/source]
[source lang="csharp"]
public static Matrix operator /(Matrix mat, float div) {
#if PERFORM_CHECKS
if (div == 0)
throw new MathematicalException(
"Divisor is zero.", new DivideByZeroException());
#endif
float num = 1f / div;
var result = Matrix.Identity;
result.M11 = mat.M11 * num;
result.M12 = mat.M12 * num;
result.M13 = mat.M13 * num;
result.M14 = mat.M14 * num;
result.M21 = mat.M21 * num;
result.M22 = mat.M22 * num;
result.M23 = mat.M23 * num;
result.M24 = mat.M24 * num;
result.M31 = mat.M31 * num;
result.M32 = mat.M32 * num;
result.M33 = mat.M33 * num;
result.M34 = mat.M34 * num;
result.M41 = mat.M41 * num;
result.M42 = mat.M42 * num;
result.M43 = mat.M43 * num;
result.M44 = mat.M44 * num;
return result;
}[/source]
Is this correct/true, and should I be doing it this way? And what other optimizations might I use in general to make my math code blazing fast and efficient?
Might I even consider doing something like this:
[source lang="csharp"]#if !PERFORM_CHECKS
unchecked {
#endif
// math code here...
#if !PERFORM_CHECKS
}
#endif[/source]