“asdf”.长度> 0 与“asdf”.Any()?

发布于 2024-09-13 23:47:49 字数 491 浏览 5 评论 0原文

数组长度 属性由内部变量(即 m_Length)标识,否则它将枚举数组的所有项目。

如果我想检查数组是否包含任何元素,就会出现差异。

Dim asdf = { "a"c, "s"c, "d"c, "f"c }
Dim any = asdf.Any()
Dim any2 = asdf.Length > 0

(另请注意,Any 是扩展方法,我想考虑调用内部 get_Length 与调用 ex 方法的性能比较。

How is an arrays Length property identified, by an internal variable (i.e. m_Length) or it's gonna enumerate thru all the items of the array.

The difference takes place if I want to check whether an array contains any elements.

Dim asdf = { "a"c, "s"c, "d"c, "f"c }
Dim any = asdf.Any()
Dim any2 = asdf.Length > 0

(Also note that Any is an extension method, and I want to take into account the performance comparison of calling the internal get_Length vs. calling an ex. method.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南街九尾狐 2024-09-20 23:47:49

代码中的 asdf 变量不是数组,而是一个 String。碰巧 String 有一个 Length 属性并实现了 IEnumerable,它允许您调用 Any()< /代码>。

尽管如此,要回答您的实际问题,确定数组的长度不需要枚举;而是需要枚举。长度存储为数组的一部分。

从技术上讲,使用 Length 比调用 Any() 更快(因为必须为数组创建一个枚举器,然后调用 MoveNext 一次) ,尽管差异可能可以忽略不计。不过,检查 Length 变量更符合约定。

The asdf variable in your code is not an array, it's a String. It just so happens that String has a Length property and implements IEnumerable<char>, which allows you to call Any().

Nonetheless, to answer your actual question, determining an array's length does not require enumeration; the length is stored as part of the array.

Technically, using Length would be faster than calling Any() (since that has to create an enumerator for the array, then call MoveNext once), though the difference is likely negligible. Checking the Length variable is more in line with convention, though.

三生殊途 2024-09-20 23:47:49

array.Length 是一个属性,也是一个 O(1) 操作。数组的长度在创建时就已知,因此在访问 Length 属性时没有理由枚举整个数组。 Any() 应该相当快,如果集合类型可以更改为任何其他 IEnumerable,那么当然很有用,但 Length 不会拖累性能。

另外,您的具体示例使用字符串而不是数组,但消息是相同的。字符串的长度在创建时已知,因此当您访问该属性时,Length 不需要枚举字符串中的字符。

array.Length is a property and an O(1) operation. An array's length is known at the time it is created, so there is no reason to enumerate the entire array when you access the Length property. Any() should be fairly fast, and certainly useful if the collection type could change to be any other IEnumerable<T>, but Length is not going to be performance drag.

Also, your specific example uses a string and not an array, but the message is the same. The length of the string is known at the time of creation, so Length would not need to enumerate the characters in the string when you access the property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文