Unity C#for和foreach效率比较

简介: 该代码对比了三种遍历 `List<int>` 的方式的性能:使用缓存 `Count` 的 `for` 循环、每次访问 `list.Count` 的 `for` 循环以及 `foreach` 循环。通过 `Stopwatch` 测量每次遍历 300 万个元素所花费的时间,并输出结果。测试可在 Unity 环境中运行,按下空格键触发。结果显示,缓存 `Count` 的 `for` 循环性能最优,`foreach` 次之,而每次都访问 `list.Count` 的 `for` 循环最慢。

比较结果如下
image.png

测试比较的代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeDuiBi : MonoBehaviour
{
    List<int> list = new List<int>();

    private void Start()
    {
        for (int i = 0; i < 3000000; i++)
        {
            list.Add(i);
        }    
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            int temp1 = 0;
            int cout = list.Count;
            for (int i = 0; i < cout; i++)
            {
                temp1 += list[i];
            }
            stopwatch.Stop();
            Debug.Log("for time=: " + stopwatch.Elapsed.TotalMilliseconds + "temp1:" + temp1);


            System.Diagnostics.Stopwatch stopwatch2 = new System.Diagnostics.Stopwatch();
            stopwatch2.Start();
            int temp3 = 0;
            for (int i = 0; i < list.Count; i++)
            {
                temp3 += list[i];
            }
            stopwatch2.Stop();
            Debug.Log("for list.Count  time=: " + stopwatch2.Elapsed.TotalMilliseconds + "temp3:" + temp3);


            System.Diagnostics.Stopwatch stopwatch1 = new System.Diagnostics.Stopwatch();
            stopwatch1.Start();
            int temp2 = 0;
            foreach (var item in list)
            {
                temp2 += item;
            }
            stopwatch1.Stop();
            Debug.Log("foreach time=: " + stopwatch1.Elapsed.TotalMilliseconds + "temp2:" + temp2);
        }
    }
}

最后可以自行运行测试

相关文章
for、foreach、stream 哪家的效率更高,你真的用对了吗?
昨天在《SQL中那么多函数,Java8为什么还要提供重复的Stream方法,多此一举?》一文中,有同学指出Stream在数据量不庞大的情况,效率不如for循环。
|
3月前
|
存储
`map()`方法在什么场景下会比 `forEach()`方法更高效?
综上所述,当需要对数组元素进行复杂的转换并生成新数组、进行链式调用和函数式编程、处理元素之间存在明确映射关系的情况以及与其他数组方法结合使用时,`map()`方法比`forEach()`方法更高效,能够使代码更加简洁、清晰和易于维护。
79 32
|
5月前
|
存储 JavaScript 前端开发
`forEach()`方法和`map()`方法哪个执行效率更高?
`forEach()`方法和`map()`方法哪个执行效率更高?
C# for和foreach两种循环的效率问题
C# for和foreach两种循环的效率问题
|
JavaScript 索引
js循环for、for...in、for...of、forEach 使用场景及优缺点
js循环for、for...in、for...of、forEach 使用场景及优缺点
113 0
|
数据采集 Java 测试技术
03-UI自动化遍历工具-appcrawler
03-UI自动化遍历工具-appcrawler
|
前端开发
前端学习案例12-数组迭代方法foreach
前端学习案例12-数组迭代方法foreach
67 0
前端学习案例12-数组迭代方法foreach
|
前端开发 算法 API
《通过减少 draw call 提升渲染性能-沧东》演讲视频 + 文字版
《通过减少 draw call 提升渲染性能-沧东》演讲视频 + 文字版
279 0
|
JSON 安全 程序员
GoFrame的gmap相比Go原生的map,天然支持排序和有序遍历
这篇文章就是给初学的小伙伴们答疑解惑的,会为大家介绍: 为什么Go语言中的map是无序的,如何自定义实现map的排序?
241 0
GoFrame的gmap相比Go原生的map,天然支持排序和有序遍历