- Unity Game Optimization
- Dr. Davide Aversa Chris Dickinson
- 387字
- 2021-06-24 12:13:07
Using distance-squared over distance
It is safe to say that CPUs are relatively good at multiplying floating-point numbers together, but relatively dreadful at calculating square roots from them. Every time we ask Vector3 to calculate a distance with the magnitude property or with the Distance() method, we're asking it to perform a square root calculation (as per Pythagorean theorem), which can cost a lot of CPU overhead compared to many other types of vector math calculations.
However, the Vector3 class also offers a sqrMagnitude property, which provides the same result as distance, only the value is squared. This means that if we also square the value we wish to compare distance against, then we can perform essentially the same comparison without the cost of an expensive square-root calculation.
For example, consider the following code:
float distance = (transform.position – other.transform.position).Distance();
if (distance < targetDistance) {
// do stuff
}
This can be replaced with the following and achieve a nearly identical result:
float distanceSqrd = (transform.position – other.transform.position).sqrMagnitude;
if (distanceSqrd < (targetDistance * targetDistance)) {
// do stuff
}
The reason the result is nearly identical is because of the floating-point precision. We're likely to lose some of the precision that we would have had from using the square root values, since the value will be adjusted to an area with a different density of representable numbers; it could land exactly on, or closer to, a more accurate representable number, or, more likely, it will land on a number with less accuracy. As a result, the comparison is not exactly the same, but, in most cases, it is close enough to be unnoticeable, and the performance gain can be quite significant for each instruction we replace in this manner.
If this minor precision loss is not important, then this performance trick should be considered. However, if precision is very important (such as running an accurate large-scale galactic space simulation), then you may want to give this tip a pass.
Note that this technique can be used for any square-root calculations, not just for distance. This is simply the most common example you might come across, and it brings to light the important sqrMagnitude property of the Vector3 class. This is a property that Unity Technologies intentionally exposed for us to make use of in this manner.
- UI圖標(biāo)創(chuàng)意設(shè)計
- C++案例趣學(xué)
- CockroachDB權(quán)威指南
- Python從入門到精通(精粹版)
- 基于差分進(jìn)化的優(yōu)化方法及應(yīng)用
- 微信公眾平臺開發(fā):從零基礎(chǔ)到ThinkPHP5高性能框架實踐
- Tableau 10 Bootcamp
- Mastering Backbone.js
- Visual C#.NET Web應(yīng)用程序設(shè)計
- 從零開始:UI圖標(biāo)設(shè)計與制作(第3版)
- C++從入門到精通(第6版)
- C++ System Programming Cookbook
- Appcelerator Titanium:Patterns and Best Practices
- MATLAB 2020 GUI程序設(shè)計從入門到精通
- Python數(shù)據(jù)預(yù)處理技術(shù)與實踐