Jump to content

Recommended Posts

Posted

I posted this on the msdn forums, but I didn't get an answer that directly relates to my question. So I'm reposting it here for you 9ers.

 

I'm currently reading "Data Structures and Algorithms using VB.Net" and in one the author's examples, he initializes an array of integers using ReDim Preserve. I was a bit confused as to why he would do that, since the array is empty. So I ran a test

initializing an array using ReDim Preserve against arry = new Integer(number){} and the ReDim Preserve was faster.

 

Here is part of the code:

 

Module Module1

 

*** Sub Main()

******* Dim arry As New CArray(9)

 

******* Dim sw = New Stopwatch()

******* sw.Start()

******* For index = 0 To 49

*********** arry.Insert(index)

******* Next

******* sw.Stop()

******* arry.showArray()

******* Console.WriteLine(sw.Elapsed)

******* Console.ReadLine()

 

*** End Sub ' Main

 

*Class CArray

 

******* Private arr() As Integer

******* Private numElements As Integer

 

******* Public Sub New(ByVal number As Integer)

 

*********** ReDim Preserve arr(number) ' faster

*********** 'arr = New Integer(number) {} ' slower

*********** 'ReDim arr(number) ' about the same as* 2nd example

*********** numElements = 0

 

******* End Sub

...

 

The ReDim Preserve averaged out at .00058 while

arry = new Integer(number){} averaged at about .0027

 

Ok, now why did the author use ReDim Preserve when the array hasn't been intialized with anything yet?

Is it because he knew that it was faster?

 

Um, they don't teach us to declare arrays like that in school or in our textbooks thats why I was confused when I saw that.

Any ideas?

 

Thanks.

 

 

More...

 

View All Our Microsoft Related Feeds

  • Replies 0
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...