2

I have a loop that checks for values and adds them to a dictionary if they do not exist. This check happens inside of a loop so it happens repeatedly. As the dictionary grows I imagine there is an inner loop going on with each check that is becoming costly. In an effort to speed up my entire routine I am wondering if this might be something I should optimize? If so, how?

  keycnt = 1
  For x = 1 to 500000
  STRVAL = returnarray(8, x)
            If Not STRDIC.Exists(STRVAL) Then
               STRDIC.Add STRVAL, keycnt
               keycnt = keycnt + 1
            End If
  next x
6
  • 2
    Where is STRVAL coming from? Without knowing that it's difficult to tell what you're asking here? In any case, the advantage of using a dictionary is that key lookups are very fast - typically lookup is via hashed keys and not just a simple loop. Commented Jun 10, 2016 at 17:26
  • It's just some value I set based on a recordset I am pulling using ADO. As I loop through the recordset I assign the value. I removed all of that to simplify my question because I don't really want anyone focusing on that. Commented Jun 10, 2016 at 17:33
  • your answer TIM is helping. That's what I am asking. Is it okay to hit the dictionary lookup repeatedly or is there a better method. Commented Jun 10, 2016 at 17:35
  • 2
    No it's designed to be hit! Commented Jun 10, 2016 at 17:39
  • 1
    A better way is to add it, it will error if it already exists. Test for the error if you care. This way you only look up the dictionary once - when it is added. Your code searches twice - once to see if it exists and then when you add it. Commented Jun 11, 2016 at 22:07

1 Answer 1

4

If your dictionary is a Scripting.Dictionary and not some [poorly implemented] custom-made data structure class, then a key lookup should be O(1) complexity, not O(n) as you seem to imply; the growing number of keys has no impact on performance.

Key lookup in a hash table or dictionary is basically free, the only thing to fix in that code is the indentation.

Sign up to request clarification or add additional context in comments.

1 Comment

yes its a Scripting.Dictionary. Thank you Mat's Mug. I wasn't sure how the lookup in the dictionary was happening and I was afraid that nesting it in a giant loop was a mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.