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:
  1. Private Function ListContains(x As Int32, y As Int32) As Boolean
  2.         If ListOfBlock.Contains(New Block(x, y)) Then
  3.             Return True
  4.         End If
  5.         Return False
  6.     End Function
  7.  
  8.     Private Function Cycle1(x As Int32, y As Int32) As Boolean
  9.         For i As Int32 = 0 To ListOfBlock.Count - 1 Step 1
  10.             If ListOfBlock(i).Equals(New Block(x, y)) Then
  11.                 Return True
  12.             End If
  13.         Next
  14.         Return False
  15.     End Function
  16.  
  17.     Private Function Cycle2(x As Int32, y As Int32) As Boolean
  18.         For i As Int32 = 0 To ListOfBlock.Count - 1 Step 1
  19.             If ListOfBlock(i).X = x And ListOfBlock(i).Y = y Then
  20.                 Return True
  21.             End If
  22.         Next
  23.         Return False
  24.     End Function