DBNull.Value.Equals() 检查的性能如何?

发布于 2024-11-01 01:36:07 字数 911 浏览 5 评论 0原文

我知道这可能还不够担心,但是 DBNull.Value.Equals() 检查的性能如何?

public IEnumerable<dynamic> Query(string sql, params object[] args)
{
    using (var conn = OpenConnection())
    {
        var rdr = CreateCommand(sql, conn, args).ExecuteReader(CommandBehavior.CloseConnection);
        while (rdr.Read())
        {
            var e = new ExpandoObject();
            var d = e as IDictionary<string, object>;
            for (var i = 0; i < rdr.FieldCount; i++)
                d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
            yield return e;
        }
    }
}

特别是这一行:

d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);

与原始代码(来自 Rob Conery 的 Massive 课程):

d.Add(rdr.GetName(i), rdr[i]);

肯定至少会产生很小的影响,同样可能不会真正引人注目,但我很好奇。进行转换的原因是因为在 ASP.NET MVC 视图中测试 null 更容易。

I know it's probably not enough to be worried about, but how performant is the DBNull.Value.Equals() check?

public IEnumerable<dynamic> Query(string sql, params object[] args)
{
    using (var conn = OpenConnection())
    {
        var rdr = CreateCommand(sql, conn, args).ExecuteReader(CommandBehavior.CloseConnection);
        while (rdr.Read())
        {
            var e = new ExpandoObject();
            var d = e as IDictionary<string, object>;
            for (var i = 0; i < rdr.FieldCount; i++)
                d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
            yield return e;
        }
    }
}

in particular, this line:

d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);

versus the original code (from Rob Conery's Massive class):

d.Add(rdr.GetName(i), rdr[i]);

There's bound to be at least a small impact, again probably not truly noticable, but I'm curious. The reason for the conversion is because it's much easier testing for null in ASP.NET MVC views.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

平生欢 2024-11-08 01:36:07

如果您查看 .NET 反射器,您会发现 DBNull 对象没有任何字段。始终有一个 DBNull 实例(静态值字段)。此外,DBNull 类中的 Equals 方法不会被重写。这意味着调用了 Object.Equals,它将执行外部方法调用来检查引用相等性。

结论:此调用正在比较两个指针,在任何情况下性能影响都不会成为问题,就像比较两个整数值一样。

If you look in .NET reflector you can see that a DBNull object does not have any fields. There is always one instance of DBNull (the static Value field). Furthermore, the Equals method is not overriden in the DBNull class. This means the Object.Equals is called which will do an external method call that checks for reference equality.

Conclusion: this call is comparing two pointers and the performance impact is not going to be an issue in any situation, it's like comparing two integer values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文