“asdf”.长度> 0 与“asdf”.Any()?
数组长度
属性由内部变量(即 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码中的
asdf
变量不是数组,而是一个String
。碰巧String
有一个Length
属性并实现了IEnumerable
,它允许您调用Any()< /代码>。
尽管如此,要回答您的实际问题,确定数组的长度不需要枚举;而是需要枚举。长度存储为数组的一部分。
从技术上讲,使用
Length
比调用Any()
更快(因为必须为数组创建一个枚举器,然后调用MoveNext
一次) ,尽管差异可能可以忽略不计。不过,检查Length
变量更符合约定。The
asdf
variable in your code is not an array, it's aString
. It just so happens thatString
has aLength
property and implementsIEnumerable<char>
, which allows you to callAny()
.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 callingAny()
(since that has to create an enumerator for the array, then callMoveNext
once), though the difference is likely negligible. Checking theLength
variable is more in line with convention, though.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 otherIEnumerable<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.