Hi!
So, I've been experimenting with lists of custom classes and trying to find the most efficient way to find if a specific object is in the list. I made 3 functions that run differently to find out which one was the most efficient. ListOfBlock contained 10,200 items. (I ran 5 trials of 10k times each.) I expected the first function to be the fastest but in fact it was not.
ListContains ran at about 1515 times per second.
Cycle1 ran at about 926 times per second.
Cycle2 ran at about 3333 times per second, the fastest by far. I was surprised because this function cycled through every item in the list.
Can someone explain to me why this method is faster than using List.Contains? Does List.Contains also cycle through every item in the list, only we don't see it?
Thanks,
~Nic
vb Code:
Private Function ListContains(x As Int32, y As Int32) As Boolean If ListOfBlock.Contains(New Block(x, y)) Then Return True End If Return False End Function Private Function Cycle1(x As Int32, y As Int32) As Boolean For i As Int32 = 0 To ListOfBlock.Count - 1 Step 1 If ListOfBlock(i).Equals(New Block(x, y)) Then Return True End If Next Return False End Function Private Function Cycle2(x As Int32, y As Int32) As Boolean For i As Int32 = 0 To ListOfBlock.Count - 1 Step 1 If ListOfBlock(i).X = x And ListOfBlock(i).Y = y Then Return True End If Next Return False End Function




Reply With Quote
