본문 바로가기
Unity3D

[Unity]FindOfjectsOfType<T> 와 GetComponents<T> 중 어떤게 더 빠를까?

by 따봉이 2020. 11. 2.
728x90
반응형

root에서 호출하는 것이 가장 빠르다

Editor

메소드 평균 처리 시간 (ms)

FindObjectOfType 10.0
FindObjectsOfType 11.0
RootGameObject 3.5
RootGameObject(List) 3.0

standalone에서 developmentbuild + Autoconnect profiler

메소드 평균 처리 시간 (ms)

FindObjectOfType 6.5
FindObjectsOfType 6.9
RootGameObject 2.7
RootGameObject(List에추가) 2.7

테스트 환경

windows7
Unity 2018.4.5f1
.net 4.x
.net standard 2.0
mono

 

 

profile.cs
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
public class NewBehaviourScript : MonoBehaviour
{
    const string ROOT_GAMEOBJECT_NO_BUFFERED = "rootGameObjects no buffered";
    const string ROOT_GAMEOBJECT_BUFFERED = "root game object buffered";
    const string FIND_OBJECTS_TYPE = "find object's of type";
    const string FIND_OBJECT_TYPE = "find object of type";

    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < 1000; i++)
        {
            var go = new GameObject($"number {i}");
            for (int y = 0; y < 20; y++)
            {
                go.AddComponent<Type1>();
                go.AddComponent<Type2>();
            }
        }
    }

    private List<Type1> _Type1s = new List<Type1>();
    private List<GameObject> GameObjects = new List<GameObject>();
    private List<Type1> _Type1sBuffer = new List<Type1>();
    // Update is called once per frame
    void Update()
    {
        GC.Collect();
        {
            Profiler.BeginSample(ROOT_GAMEOBJECT_NO_BUFFERED);
            var rootGameObjects = gameObject.scene.GetRootGameObjects();
            Type1[][] type1s = new Type1[rootGameObjects.Length][];
            for (int i = 0; i < rootGameObjects.Length; i++)
            {
                type1s[i] = rootGameObjects[i].GetComponentsInChildren<Type1>();
            }
            Profiler.EndSample();
        }
        GC.Collect();
        {
            Profiler.BeginSample(ROOT_GAMEOBJECT_BUFFERED);
            gameObject.scene.GetRootGameObjects(GameObjects);
            for (int i = 0; i < GameObjects.Count; i++)
            {
                GameObjects[i].GetComponentsInChildren(_Type1sBuffer);
                _Type1s.AddRange(_Type1sBuffer);
            }
            Profiler.EndSample();
            _Type1sBuffer.Clear();
            _Type1s.Clear();
            GameObjects.Clear();
        }
        GC.Collect();
        {
            Profiler.BeginSample(FIND_OBJECTS_TYPE);
            var type1s = GameObject.FindObjectsOfType<Type1>();
            Profiler.EndSample();
        }
        GC.Collect();
        {
            Profiler.BeginSample(FIND_OBJECT_TYPE);
            var type1 = GameObject.FindObjectOfType<Type1>();
            Profiler.EndSample();
        }
    }
}

//별도 파일로 정의
public class Type1 : MonoBehaviour
{
}
public class Type2 : MonoBehaviour
{
}

 

 

728x90
반응형

댓글