开发者

I've got 3 ways to get the ubound of an array

开发者 https://www.devze.com 2023-03-07 02:52 出处:网络
I\'ve got this 3 piece of code: For x = 0 To sections.Length - 1 \'work Next For x = 0 To UBound(sections)

I've got this 3 piece of code:

 For x = 0 To sections.Length - 1
        'work
    Next
    For x = 0 To UBound(sections)
        'work
    Next
    For x = 0 To sect开发者_运维技巧ions.GetUpperBound(0)
        'work
    Next

I've been thinking for about 10 minutes but I still can't decide what exactly are the advantages of 1 choice over the other.

I was wondering if anyone has actually given this some thought and would like to share their insights. Basically I would like to know which is "better" (you can quote clarity, easy refactoring, performance, maintainability, good standard, anything that makes it "better")


I'm assuming you need to use the index within the loop - otherwise, just use a For Each loop instead.

1 is the idiomatic way for a single-dimensional array, in my view. It's the closest to the normal way you'd see in C#:

for (int x = 0; x < array.Length; x++)

It's unfortunate that VB has this slight dual personality these days in terms of whether it's zero or one-based. .NET is generally a zero-based platform, and you're suffering for it here; languages designed around zero-based APIs are likely to make the "inclusive lower-bound; exclusive upper-bound" pattern simpler - whereas VB is inclusive at both ends, which is why you need the "-1".

2 looks like it's a VB-specific function; I would try to avoid these unless they present significant advantages, as it will make it harder for non-VB programmers (e.g. C# programmers) to understand the code. That's only a very minor concern in many cases, but when there are no real advantages to it, I'd stick with "regular" .NET approaches.

3 is really designed for multi-dimensional (rectangular) arrays - the 0 there is saying that you want the first dimension. When you're dealing with single-dimensional arrays it's adding extra complexity for no good reason.

It's possible that the first approach is also the most performant - the JIT recognizes this pattern and is able to remove some array bounds tests within the loop (it knows that x is within the bounds of the array). Now UBound may compile to IL that has the same property - I'm not sure. I suspect it makes a call to a method within the Microsoft.VisualBasic assembly, which the JIT is less likely to have knowledge of.


It basically depends on the semantics of what you are doing. Choose whichever one most clearly expresses what you're doing in the code.


I prefer the third one because it's most clear what you're measuring - you're getting the upper bound of the first index of the array "sections". The others describe the same thing, but I don't think they do it as clearly.

0

精彩评论

暂无评论...
验证码 换一张
取 消