2

I'm dealing with big arrays, lots get dynamically created and destroyed as it is. Now i'm starting to build the processing bit of the class and want to avoid as much unnecessary slowdowns as possible.

My specific question would be: If I create a function that fetches an array by its name, would it pass on the reference to the array(desired) or create a duplicate array and give out that instead? Is there any way to control this?

Here is the code I am working with:

 public function fetchArrayByName(name as string) as single()
      for i = 0 to channels.count-1
           if channelnames(i) = name then return channel(i)
      next i
      return nothing
 end function
4

3 回答 3

2

如果未指定,则隐含 ByVal,但它实际上是对数组的引用。所以你不能覆盖方法内的指针,但你可以改变它指向的对象。综上所述,数组和类一样,实际上是通过引用传递的,不会创建重复的数组。

官方参考:值类型和引用类型

非官方的,有用户评论:VB.NET 中的数组 ByVal 还是 ByRef?

于 2013-09-05T20:54:55.033 回答
0

也许一个例子会有所帮助:

Module Module1

    Dim channels As New Dictionary(Of String, Single())
    Function GetChannel(name As String) As Single()
        If channels.ContainsKey(name) Then
            Return channels(name)
        End If
        Return Nothing

    End Function

    Function GetShallowCopyOfChannel(name As String) As Single()
        If channels.ContainsKey(name) Then
            'TODO: if a deep clone is required, implement it.
            Dim newChannel = channels(name).Clone()
            Return CType(newChannel, Single())
        End If
        Return Nothing

    End Function
    Sub Main()

        channels.Add("English", {1.1, 2.2, 3.3, 4.4})
        channels.Add("Columbia River", {10.01, 11.11, 12.21, 13.31})

        Dim ch = GetChannel("English")

        If ch IsNot Nothing Then
            ch(0) = 999
            ' shows 999 as the first element, i.e. ch is the original array
            Console.WriteLine(String.Join(", ", channels("English")))
        Else
            'something went wrong
        End If

        ch = GetShallowCopyOfChannel("Columbia River")
        If ch IsNot Nothing Then
            ch(0) = 17
            ' shows 10.01 as the first element, i.e. ch is not the original array
            Console.WriteLine(String.Join(", ", channels("Columbia River")))
            ' shows 17 as the first element, i.e. ch is a an array separate from the original
            Console.WriteLine(String.Join(", ", ch))
        Else
            'something went wrong
        End If

        Console.ReadLine()

    End Sub

End Module

如果您担心不必要的减速并且您有很多数组,您可能希望使用 Dictionary 来存储数组,因为它是作为哈希表实现的。

于 2013-09-05T21:15:50.050 回答
0

数组是 .NET 中的引用类型,因此您的函数将返回对数组的引用。

如果你想要一个全新的阵列,你必须自己制作一个副本。

于 2013-09-05T20:55:05.823 回答