Consider the following code:
Dim arr1 As New List(Of Double)
Dim arr2 As New List(Of Object)
Dim timeStart As DateTime = Now
For x As Integer = 0 To 1000000
arr1.Add(3.14159)
Next
Dim timeEnd As DateTime = Now
MsgBox(((timeEnd - timeStart).Seconds).ToString())
timeStart = Now
arr2.Add(New List(Of Double))
For x As Integer = 0 To 1000000
arr2(0).add(3.14159)
Next
timeEnd = Now
MsgBox(((timeEnd - timeStart).Seconds).ToString())
It involves 2 lists. The first one is 1-dimensional, the second one is 2-dimensional.
The first routine (which operates on the first list) completes in about .015 seconds. The second routine (which operates on the second list), however, takes almost 10 seconds. The only difference is that the second list is 2-dimensional.
Am I missing something here? Is there a way to speed this up or am I doing something wrong? I have a program that requires several 2-dimensional arrays and it's running extremely slow right now. How can I speed it up so I get the same feedback that I'd get if the lists were 1-dimensional?
The problem lies with one line of code.
Make arr2 strongly typed and it'll be much, much faster...
Dim arr2 As New List(Of List(Of Double))
I ran a quick test and it went from about 7 seconds on my computer to 17 ms with this one change.
As CodeInChaos correctly pointed out, the reason for the slowness has more to do with the .Add()
method being dynamically dispatched than anything.
EDIT: Writing VB.NET with Option Strict On is one way to avoid this kind of problem in the future. By doing this, you would've seen a compile-time error that says "Option Strict On disallows late binding."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With