Is it costly to do array.length or list.count in a loop(在循环中执行 array.length 或 list.count 成本高吗)
问题描述
我知道在 JavaScript 中,创建这样的 for 循环:for(int i = 0; i < arr.length; i++)
成本很高,因为它每次都会计算数组长度.对于列表和数组,这种行为在 c# 中是否也很昂贵.还是在编译时进行了优化?还有Java等其他语言呢,这是怎么处理的?
I know that in JavaScript, creating a for loop like this: for(int i = 0; i < arr.length; i++)
is costly as it computes the array length each time.
Is this behavior costly in c# for lists and arrays as well. Or at compile-time is it optimized? Also what about other languages such as Java, how is this handled?
推荐答案
在 C# 中不成本很高.一方面,没有计算":由于内联,查询长度基本上是一个基本操作.其次,因为(根据其开发人员的说法),编译器会识别这种访问模式,实际上会优化任何(冗余)边界检查以访问数组元素.
It is not costly in C#. For one thing, there is no "calculation": querying the length is basically an elementary operation thanks to inlining. And secondly, because (according to its developers), the compiler recognizes this pattern of access and will in fact optimize any (redundant) boundary checks for access on array elements.
顺便说一句,我相信现代 JavaScript 虚拟机也有类似的情况,如果现在还没有,那么很快就会出现,因为这是一个微不足道的优化.
And by the way, I believe that something similar is true for modern JavaScript virtual machines, and if it isn't already, it will be very soon since this is a trivial optimization.
这篇关于在循环中执行 array.length 或 list.count 成本高吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在循环中执行 array.length 或 list.count 成本高吗
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01