Game Development

Unity 자식 클래스 참조 성능 비교 본문

Unity/Performance

Unity 자식 클래스 참조 성능 비교

Dev Owen 2021. 6. 29. 19:21

자식 클래스 참조 성능 비교

상속받는 클래스 자식을 참조하는 방법 중 GetComponet와  as를 통하여 자식을 참조 할 수 있습니다.

여기서 GetComponet 와 as의 성능을 비교해 보도록 하겠습니다.


테스트

두 방식을 통한 속도의 차이를 알아보는 테스트 입니다. 천 만번 아래의 코드를 실행 했을 경우 서로의 속도를 비교해 보도록 하겠습니다.

GetComponet를 통한 방식

[SerializeField] TestParent test;

int count = 10000000;
private void Awake() {
    TestChild test2;
    sw.Start();
    for ( int i = 0; i < count; i++ )
    {
        test2 = test.GetComponent< TestChild >();        
    }
    sw.Stop();
    UnityEngine.Debug.Log(sw.ElapsedMilliseconds.ToString());
}

as 를 통한 방식

[SerializeField] TestParent test;

int count = 10000000;
private void Awake() {
    TestChild test2;
    sw.Start();
    for ( int i = 0; i < count; i++ )
    {
        test2 = test as TestChild;
    }
    sw.Stop();
    UnityEngine.Debug.Log(sw.ElapsedMilliseconds.ToString());
}
GetComponet as
1382 ms 2 ms

결과

사실 당연한 결과이다 GetComponet는 오브젝트의 있는 모든 컨퍼넌트를 검사해야 하지만 as는 해당 스크립트만 검사하면 되기에 속도차이가 나는것이 당연하다. 다들 자식 참조하는건 as를 사용합시다.

Comments