Floating-point division is expensive on old hardware. A common optimization is replacing division with multiplication using reciprocal values.
| Division | Optimized Multiplication | Example |
|---|---|---|
| x / 2 | x * 0.5f | value * 0.5f |
| x / 4 | x * 0.25f | value * 0.25f |
| x / 8 | x * 0.125f | value * 0.125f |
| x / 16 | x * 0.0625f | value * 0.0625f |
| x / 32 | x * 0.03125f | value * 0.03125f |
| x / 64 | x * 0.015625f | value * 0.015625f |
Integer division by powers of two can be replaced with bit shifts. This is extremely fast on old CPUs.
| Division | Bit Shift | Example |
|---|---|---|
| x / 2 | x >> 1 | value >> 1 |
| x / 4 | x >> 2 | value >> 2 |
| x / 8 | x >> 3 | value >> 3 |
| x / 16 | x >> 4 | value >> 4 |
| x / 32 | x >> 5 | value >> 5 |
| x / 64 | x >> 6 | value >> 6 |
// Floating point optimization
float half = value * 0.5f;
// Integer optimization
int halfInt = value >> 1;
// Vector normalization optimization
float invLength = fastInvSqrt(x*x + y*y);
x *= invLength;
y *= invLength;