包含VS尝试捕获 [英] Containskey VS Try Catch

查看:93
本文介绍了包含VS尝试捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Vector2的Generated列表,我必须检查一个字典以查看它们是否存在,该函数每执行一次就会执行一次.

I have a list of Vector2's Generated I have to check against a dictionary to see if they exist, this function gets executed every tick.

哪种方法运行最快/这样做会更好?

which would run fastest/ be better to do it this way?

    public static bool exists(Vector2 Position, Dictionary<Vector2, object> ToCheck)
    {
        try
        {
            object Test = ToCheck[Position];
            return (true);
        }
        catch 
        {
            return (false);
        }           
    }

还是我应该遵守准则?

    public static bool exists(Vector2 Position, Dictionary<Vector2, object> ToCheck)
    {
        if (ToCheck.ContainsKey(Position))
        {
            return (true);
        }
        return (false);
    }

感谢您的输入:)

侧面注意:(此时的键值无关紧要,否则我将使用TryGetValue而不是ContainsKey)

Side Note: (The Value for the key doesn't matter at this point or i would use TryGetValue instead of ContainsKey)

推荐答案

绝对使用ContainsKey检查;异常处理可能会添加大量开销.

Definitely use the ContainsKey check; exception handling can add a large overhead.

抛出异常会对性能产生负面影响.对于通常会失败的代码,可以使用设计模式来最大程度地减少性能问题.

Throwing exceptions can negatively impact performance. For code that routinely fails, you can use design patterns to minimize performance issues.

异常不能用于您可以检查的条件.

Exceptions are not meant to be used for conditions you can check for.

我建议阅读一般情况下的例外的MSDN文档. ,尤其是异常处理.

I recommend reading the MSDN documentation on exceptions generally, and on exception handling in particular.

这篇关于包含VS尝试捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆