Unity 两种遍历子物体方式的性能比较

之前我获取GameObject所有的子物体都是用的transform.GetChild(index),最近在网上看到了一种新的获取所有子物体方式,是通过foreach父物体的transform来实现的。
foreach获取子物体代码

        foreach(Transform tf in transform)
        {
            //do something
        }

如果我使用原来的方法,就应该是

        for(int i = 0; i < transform.childCount; ++i)
        {
            Transform tf = transform.GetChild(i);
        }

我想测试一下两者的效率差距,测试代码如下

        int count = 0;

        Stopwatch watch = new Stopwatch();
        watch.Start();
        for(int i = 0; i < transform.childCount; ++i)
        {
            Transform tf = transform.GetChild(i);
            ++count;
        }
        watch.Stop();

        TimeSpan time = watch.Elapsed;
        UnityEngine.Debug.Log("for - " + time.TotalMilliseconds.ToString() + " - " + count.ToString());

        count = 0;
        watch.Restart();
        foreach(Transform tf in transform)
        {
            //do something
            ++count;
        }
        watch.Stop();

        time = watch.Elapsed;
        UnityEngine.Debug.Log("foreach - " + time.TotalMilliseconds.ToString() + " - " + count.ToString());

通过观察两者的运行时间来判断执行效率(两者都可以找到子物体的子物体,即父物体下面的所有子物体)
我在Scene中放置了1w+个空GameObject,给他们一个共有的父物体,从这个父物体出发去寻找遍历这些子物体的transform
结果如下
image

可以看到foreach效率要更高些,所以以后遍历所有子物体建议用foreach

posted @ 2021-12-22 10:35  可乐社区  阅读(768)  评论(0)    收藏  举报