DBNull.Value.Equals() 检查的性能如何?
我知道这可能还不够担心,但是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您查看 .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.