none
Minimizing processor usage when checking if dictionary contains a key? RRS feed

  • Question

  • Which one is fastest?

    This:

                            If Not dChannels.Keys.Contains(i) Then
                                dChannels.Add(i, Frame.ChannelDefinitions(i))
                            End If

    ... or this:

                            Dim x As clsChannel
                            If Not dChannels.TryGetValue(i, x) Then
                                dChannels.Add(i, Frame.ChannelDefinitions(i))
                            End If

    where i is the key to look for.

    Friday, February 8, 2013 10:53 PM

Answers

  • Contains will be faster in this case, since you're not using the results of TryGetValue.

    If you were going to use the results, then TryGetValue would be better.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Mike FengModerator Monday, February 11, 2013 11:23 AM
    • Marked as answer by MikaelJ__SE Wednesday, February 13, 2013 8:44 PM
    Friday, February 8, 2013 11:28 PM
    Moderator
  • The docs say this about that:

    Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property.

    Makes sense because an interrupt takes lots of time.

    Hope this helps

    LS 


    Lloyd Sheen

    • Proposed as answer by Mike FengModerator Monday, February 11, 2013 11:23 AM
    • Marked as answer by MikaelJ__SE Wednesday, February 13, 2013 8:43 PM
    Friday, February 8, 2013 11:20 PM

All replies

  • The docs say this about that:

    Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item property.

    Makes sense because an interrupt takes lots of time.

    Hope this helps

    LS 


    Lloyd Sheen

    • Proposed as answer by Mike FengModerator Monday, February 11, 2013 11:23 AM
    • Marked as answer by MikaelJ__SE Wednesday, February 13, 2013 8:43 PM
    Friday, February 8, 2013 11:20 PM
  • Contains will be faster in this case, since you're not using the results of TryGetValue.

    If you were going to use the results, then TryGetValue would be better.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Mike FengModerator Monday, February 11, 2013 11:23 AM
    • Marked as answer by MikaelJ__SE Wednesday, February 13, 2013 8:44 PM
    Friday, February 8, 2013 11:28 PM
    Moderator
  • Thank you both! Much appreciated. :)
    Wednesday, February 13, 2013 8:45 PM