Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

前端 未结 2 1558
失恋的感觉
失恋的感觉 2020-12-12 10:08

Imagine the code:

public class obj
{
    // elided
}

public static Dictionary dict = new Dictionary();
相关标签:
2条回答
  • 2020-12-12 10:39

    On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
    On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

    BTW: The correct way to do this is to use TryGetValue

    obj item;
    if(!dict.TryGetValue(name, out item))
        return null;
    return item;
    

    This accesses the dictionary only once instead of twice.
    If you really want to just return null if the key doesn't exist, the above code can be simplified further:

    obj item;
    dict.TryGetValue(name, out item);
    return item;
    

    This works, because TryGetValue sets item to null if no key with name exists.

    0 讨论(0)
  • 2020-12-12 10:41

    Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

    0 讨论(0)
提交回复
热议问题