VB.NET: a two-dimensional list is almost 1000 times slower than a one-dimensional list?

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 includes 2 lists. The first is one-dimensional, the second is two-dimensional.

The first procedure (which works in the first list) completes in about 0.015 seconds. The second procedure (which works in the second list), however, takes almost 10 seconds. The only difference is that the second list is 2-dimensional.

Am I missing something? Is there a way to speed this up or am I doing something wrong? I have a program that requires several two-dimensional arrays, and now it works very slowly. How can I speed it up to get the same reviews as me if the lists were one-dimensional?

+4
source share
1 answer

The problem is one line of code.

Make arr2 strongly typed and it will be much, much faster ...

 Dim arr2 As New List(Of List(Of Double)) 

I checked the 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 slowness is more related to the .Add() method, which is dynamically dispatched than anything.

EDIT: Writing VB.NET with Option Strict On is one way to avoid this problem in the future. By doing this, you would see a compile-time error that says: "Option Strict On prohibits late binding."

+8
source

Source: https://habr.com/ru/post/1339448/


All Articles