问题描述
我知道在 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 成本高吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)