2

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.

Chaddeus
  • 13,134
  • 29
  • 104
  • 162
  • do 1000 queries, time the difference - I'd be surprised if you can – BrokenGlass Apr 11 '11 at 14:55
  • 1
    Would suggest that this would never, ever, ever, ever become an issue, and if it did, it would be because of an awful, maliciously-written algorithm that called DBNull.Value.Equals in a loop a million times for each call – Kieren Johnstone Apr 11 '11 at 15:06
  • Thanks Kieren. I kind of had that feeling, but thought maybe I read somewhere that DBNull.Value.Equals was "expensive". Glad that's not true. – Chaddeus Apr 11 '11 at 15:09

1 Answers1

4

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.

Bas
  • 26,772
  • 8
  • 53
  • 86