在循环中执行 array.length 或 list.count 成本高吗 [英] Is it costly to do array.length or list.count in a loop

查看:20
本文介绍了在循环中执行 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 成本高吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆