字符串数组行为:对于使用VB.NET的字符串数组中的每个操作

Pan*_*zza 0 .net vb.net arrays string foreach

我想知道在使用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
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 5

"装"是什么意思?你只是迭代数组.这不会"加载"任何东西 - 它只是迭代它.它不会复制,如果这是你担心的.

至少在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
Run Code Online (Sandbox Code Playgroud)

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

与什么相反?例如,最好这样做,而不是每次重新查询数据库.但是将a转换List(Of String)为字符串数组是不值得的......