유니티 인증 시험에서 출제된 문제중 하나입니다.
최적화 관련된 질문을 하는 경우에 반드시 출제될 내용으로 보시면 됩니다.
https://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html
https://docs.unity3d.com/ScriptReference/Vector3-magnitude.html
Unity - Scripting API: Vector3.sqrMagnitude
The magnitude of a vector v is calculated as Mathf.Sqrt(Vector3.Dot(v, v)). However, the Sqrt calculation is quite complicated and takes longer to execute than the normal arithmetic operations. Calculating the squared magnitude instead of using the magnitu
docs.unity3d.com
내용을 확인해보면, 결국 이 이야기를 하는것입니다.
sqrMagnitude : 거리 값을 구하는 연산에서 루트 연산을 제외한 값.
magnitude : 거리 값.
공식 문서에서도 정확한 거리를 알아야 하는 경우가 아니라 단순 크기 비교를 하는 경우에는 sqrMagnitude를 사용하라고 권장됩니다. 그 이유는 컴퓨터가 처리하기에는 루트 연산이 아주 무겁기 때문인데, 얼마나 무거운지 직접 실험을 해보겠습니다.
실험을 위해 다음과 같은 코드를 작성하였습니다.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class sqrtTest : MonoBehaviour
{
private Vector3 _from = new Vector3(500f, 100f, 40f);
private Vector3 _to = new Vector3(-30f, 200f, -440f);
private Vector3 _from2 = new Vector3(500f, 100f, 40f);
private Vector3 _to2 = new Vector3(-30f, 200f, -440f);
// Start is called before the first frame update
void Start()
{
Stopwatch sw = new Stopwatch();
Vector3 result = _to - _from;
Vector3 result2 =_to2 - _from2;
sw.Start();
for (int i = 0; i < 1000000; i++)
{
if (result.sqrMagnitude < result2.sqrMagnitude)
{
Debug.Log("result2가 더 큽니다.");
}
}
sw.Stop();
Debug.Log($"sqrMagnitude Time(ms) : {sw.ElapsedMilliseconds}ms");
sw.Restart();
for (int i = 0; i < 1000000; i++)
{
if (result.magnitude < result2.magnitude)
{
Debug.Log("result2가 더 큽니다.");
}
}
sw.Stop();
Debug.Log($"magnitude Time(ms) : {sw.ElapsedMilliseconds}ms");
}
// Update is called once per frame
void Update()
{
}
}
동일한 조건에서 10만번 진행하였습니다.
하나는 sqrMagnitude를 사용하여 거리 비교를 진행하였고, 이어서 magnitude를 이용하여 거리 비교를 진행하였습니다.
결과는 어떨까요?
절대적인 수치는 PC의 상태에 따라 달라질 수 있지만 차이를 보면 확연히 속도가 다른 것을 알 수 있습니다.
따라서, 꼭 거리 값이 정확하게 필요한 경우가 아니라 어느쪽이 더 큰지만 알아도 된다면, 반드시 sqrMagnitude를 사용하도록 하는것이 바람직하다는 결론이 될 수 있습니다.
개발 및 시험에 참고 바랍니다.