Comparing Lengths vs Comparing Squared Lenghts

Hi,

I’m just sharing here a good practice:

If you only need to compare lengths of some vectors, you can compare squared length of them using sqrMagnitude. Computing squared magnitudes is much faster: it only calculates x * x + y * y + z * z, instead of the square root of x * x + y * y + z * z.

float sqrMagnitudeBeforeMoving = (transform.position - targetPosition).sqrMagnitude;
transform.position += moveSpeed * Time.deltaTime * moveDir;
float sqrMagnitudeAfterMoving = (transform.position - targetPosition).sqrMagnitude;

if (sqrMagnitudeBeforeMoving < sqrMagnitudeAfterMoving) {
	...
}

Source

4 Likes

Yup good performance tip!

1 Like

I hear this performance tip brought up again and again and while it is true that calculating the length of a vector is more expensive than calculating/comparing the squared magnitude, you have to consider it in the context of where it is used.

For this game, I hardly think you need to worry about the performance of using square roots in the calculation of lengths of vectors. Sure, if you have to calculate the length of a vector each frame many times, there will probably be a perfomance issue, but in a turn-based game most of the logic happens for one unit once per frame, it is hardly worth the effort.

Again, do not prematurely optimize. If you do not have a performance issue, don’t optimize :slight_smile:

3 Likes

Yes, you’re right! Here, it doesn’t make any difference.
As mentioned, this tip is not an optimization, it’s just good practice.

1 Like

It is an optimization to be aware of. From a processor perspective, multiplication is always faster than division, and the multiplication already had to happen anyways, in other words, to get Vector3.magnitude, Vector3.sqrMagnitude must first be calculated. While this isn’t noticeable in an event based calculation, it can make quite a difference in Update() methods, saving over 1/2 of the calculation time.

3 Likes

@Brian_Trotter You are absolutely right. Always be aware of how you can write code in the most optimal - but also readable - way. As I stated above, I would not consider this optimisation here considering it is not done thousands of times per frame. If you had a big RTS game with many units moving at the same time, it would be an obvious choice to optimize this.

Privacy & Terms