简体   繁体   中英

Is it costly to do array.length or list.count in a loop

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?

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.

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.

  1. All .Net arrays have a field containing the length of the array, so the length is not computed at usage but at creation time.

  2. The .Net virtual machine is very good at eliminating bounds checks whenever possible, this is one of those cases, where the bounds check is moved outside the loop (in most situations, and if not it's just 2 instructions overhead).

Edit:

Array Bounds Check Elimination

In almost any language, the answer will be "it depends".

Mostly, it depends on whether the compiler is clever enough to be able to tell whether the length of the list or array might change whilst you're in the loop.

That's unlikely to be defined by the language specification, though.

So, it's probably safe to assume that the compile may not be able to figure that out. If you really truly believe that the length of the object won't change, feel free to calculate the length first and use that in your loop control constructs.

But beware of other threads...

If it's anything like Java, it should be an O(1) operation.

I found the following link helpful: http://www.devguru.com/Technologies/Ecmascript/Quickref/array.html

它还取决于该getter是进行计算还是访问已知值。

我相信如果你使用Linq Count()扩展方法,那么它可以在每次调用它时计算。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM