【问题标题】:String array behavior: For Each operation in string array using VB.NET字符串数组行为:对于使用 VB.NET 的字符串数组中的每个操作
【发布时间】:2012-04-27 09:03:48
【问题描述】:

我想知道在其中使用 For Each 循环时字符串数组的行为。考虑以下代码:

Dim StringArray(499) As String
'fill in each element with random string

Dim count As Int32
Dim current As String

For Each current in StringArray
    'do something with current
    count = count + 1
    If count = 10
        Exit For
    End If
Next

're-enter the StringArray again
count = 0
For Each current in StringArray
    'do something with current
    count = count + 1
    If count = 10
        Exit For
    End If
Next

如上面的代码所示,如​​果我需要使用 For Each 循环 访问 StringArray 两次,那么 StringArray 中的 ALL 元素是否会被加载两次,即使我在每个 For Each 循环 中只使用 10 个元素?从性能的角度来看,是否建议使用字符串数组作为数据结构来存储需要多次访问的字符串列表,例如在一个方法中访问 20 次?

【问题讨论】:

  • 快速提问:“将被加载两次”你说的加载是什么意思?从哪里加载?

标签: .net vb.net arrays string foreach


【解决方案1】:

“加载”是什么意思?您只是在遍历数组。这不会“加载”任何东西——它只是迭代它。如果您担心的话,它不会复制。

至少在 C# 中,foreach 循环在编译时已知为数组的表达式上将基本上保留(并增加)索引并使用直接数组访问。它甚至不会创建IEnumerator(Of T)。我希望 VB 的行为方式相同。

请注意,LINQ 可以使您的示例代码更简单:

' No need to declare any variables outside the loop
For Each current As String in StringArray.Take(10)
    ' Do something with current
Next

从性能的角度来看,是否建议使用字符串数组作为数据结构来存储需要多次访问的字符串列表,例如在一个方法中访问 20 次?

相对于什么?例如,这样做比每次都重新查询数据库要好。但是不值得将List(Of String) 转换为字符串数组...

【讨论】:

    猜你喜欢
    • 2015-01-19
    • 2018-07-14
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多