Larry said:
OK, I'm [probably] going to rekindle a Religious War here but,
hopefully, learn something at the same time ...
In VB6, I'd have done [something like] this:
Dim sSearch As String = "1,2,3,4,5,6,7,8,9"
Dim sTarget As String = "4"
If ("," & sSearch & ",").IndexOf("," & sTarget & ",") > -1 Then
. . .
End If
Is this horribly, horribly wrong in our Brave New World?
As with most things, the best option when faced with a number of alternatives
is to test them against each other. I was expecting to recommend the .Contains
method mentioned by Larry Lard, but my test rig shows that it is the slowest
option. I did need to make some tweaks (most notably in GhostInAK's post
which returned true only if the item was not in the search pattern). I also
made some optomizations to pre evaluate items which didn't change for each
iteration of the test.
Essentially in each test, I am testing the values 0-10 against a list of
numbers 1-9 to see if they match, if so, add them to a running total of successful
matches. I am running this test 1000 times for each variant to try to get
a significant result. The results are similar if I change the number of iterations
to 1 or 1,000,000. Feel free to try this for yourself to see if you can come
up with a better algorhythm. Naturally, there is often a trade-off between
performance and maintainablility. You will need to determine which option
is the best for your situation.
Here is my test rig (using 2005):
Public Shared Sub Main()
Const IterationCount As Integer = 1000
Dim sw As New Stopwatch
Dim Pattern As String = "1,2,3,4,5,6,7,8,9"
Dim PatternArray() As String = Pattern.Split(",")
Dim CountSuccess As Integer
Console.Write("method1: ")
sw.Start()
For iterations As Integer = 1 To IterationCount
For TestItem As Integer = 0 To 10
If Not (Array.IndexOf(PatternArray, TestItem.ToString) =
-1) Then
CountSuccess += 1
End If
Next
Next
sw.Stop()
Console.WriteLine(sw.ElapsedTicks.ToString)
Console.Write("method2: ")
sw.Start()
Dim TestPattern As String = "," & Pattern & ","
For iterations As Integer = 1 To IterationCount
For TestItem As Integer = 0 To 10
If TestPattern.IndexOf("," & TestItem.ToString & ",") > -1
Then
CountSuccess += 1
End If
Next
Next
sw.Stop()
Console.WriteLine(sw.ElapsedTicks.ToString)
Console.Write("method3: ")
Dim Test3PatternList As IList = Pattern.Split(","c)
sw.Start()
For iterations As Integer = 1 To IterationCount
For TestItem As Integer = 0 To 10
If Test3PatternList.Contains(TestItem.ToString) Then
CountSuccess += 1
End If
Next
Next
sw.Stop()
Console.WriteLine(sw.ElapsedTicks.ToString)
Console.WriteLine("Total success: " & CountSuccess.ToString)
Console.WriteLine("Total should equal: " & (9 * 3 * IterationCount).ToString)
Console.ReadLine()
End Sub
Here are the results when run in release mode:
method1: 22803
method2: 57436
method3: 88614
Total success: 27000
Total should equal: 27000
Jim Wooley
http://devauthority.com/blogs/jwooley/default.asp