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

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

问题描述

我知道在JavaScript中,创建一个像这样的for循环: for(int i = 0; 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天全站免登陆