Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

having a problem. Efficiency. I know very little about efficiency in coding, but I'm learning. Searching through these arraylists of strings for item1 and when found adding item2 to a new arrayList. The logic is great. Works fine. But takes about 30-40 seconds as there are 700 elements in arrLoList * 10 000 elements in arrCoList.

Now contains drops out as soon as it finds the item1, so I can't really improve on that. Would it help at all to cut some characters off the end of the arrCoList's strings?

How else could I improve this? I think changing from arrayLists?

For Each item1 In arrLoList             
        For Each item2 In arrCoList

            If arrCoList.contains(item1) Then

                arrNewList.Add(item2)


            Else
                intCouldntfind += 1     'not finding 7 million 

            End If
share|improve this question

2 Answers

up vote 2 down vote accepted

First, i would not use an old ArrayList which always requires to box/unbox the objects to their actual type(string here). Instead i would use a strongly typed List(Of String).

Second, you can use Enumerable.Except to get the set difference which is quite efficient since it uses a HashSet internally.

Dim sw = New System.Diagnostics.Stopwatch ' measure time 
Dim rnd As New Random ' create random strings
Dim loList = New List(Of String)(700)
Dim coList = New List(Of String)(10000)

' initialize with sample data
For i = 1 To 700
    loList.Add(String.Format("Item: {0} Random-Value: {1}", i, rnd.Next(1, 1000)))
Next
For i = 1 To 10000
    coList.Add(String.Format("Item: {0} Random-Value: {1}", i, rnd.Next(1, 1000)))
Next

sw.Start()

' *** Here is all you need: '
Dim newList = loList.Except(coList).ToList()

sw.Stop()

Result: 3 milliseconds at a max

share|improve this answer

You are doing an innecesary nesting:

This should be quite a bit faster:

For Each item1 In arrLoList   
    If arrCoList.contains(item1) Then          
        For Each item2 In arrCoList               
            arrNewList.Add(item2)
        Next  
     End If
Next
share|improve this answer
Thanks for this, very helpful, just not sure it works for me, as the .contains method doesn't find anything (what i'm searching for is part of a longer string eg 10815fmelmflw lwmflemkwl. So using the first 5 letters. Contains therefore doesn't find anything for me like this). – Jonny Apr 22 at 8:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.