它是昂贵的做array.length或list.count在一个循环 [英] Is it costly to do array.length or list.count in a loop

查看:138
本文介绍了它是昂贵的做array.length或list.count在一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,在JavaScript中,像这样循环创建一个:的for(int i = 0; I< arr.length;我++)是昂贵的,因为它计算每次数组的长度。
是这种行为在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天全站免登陆