3
var item = "" + dr["someString"];

Or

var item = Convert.ToString(dr["somestring"]);

What are the performance implications of the above examples?

Leigh Ciechanowski
  • 1,297
  • 17
  • 33

2 Answers2

8

How about:

var item = (string)dr["someString"] ?? "";

which avoids an unnecessary concatenation, an unnecessary virtual call, and avoids the risk of calling a method on a null reference. It isn't clear what dr is in this context; if it is a data-reader (IDataReader etc) you might need:

int index = dr.GetOrdinal("someString");
var item = dr.IsDBNull(index) ? "" : dr.GetString(index);

or in the case of a DataTable, something involving DataRow.IsNull.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • In this example its a DataRow – Leigh Ciechanowski Mar 09 '12 at 11:48
  • @Leigh of course, I'm not a fan of `DBNull` in the first place, but in the context of a `DataRow` you *could* use `dr.IsNull(...)`. It won't change the answer, but [some related notes](http://stackoverflow.com/questions/4958379/what-is-the-difference-between-null-and-system-dbnull-value/9632050#9632050) that you might find interesting. – Marc Gravell Mar 09 '12 at 11:51
  • @Leigh as an aside, it also shows the importance of including all relevant context in a question; in this case, it **really matters** what `dr` is defined as, so it would be useful to volunteer that in the question ;p – Marc Gravell Mar 09 '12 at 11:53
  • Cool so I can conclude that casting the object to a sting and checking if its null will be better for performance than just concatenating the object with an empty string? – Leigh Ciechanowski Mar 09 '12 at 12:09
  • @LeighCiechanowski well, the concat involves extra unnecessary steps - however, in the case of DataRow it won't be `null`, but `DbNull`, which is more work – Marc Gravell Mar 09 '12 at 12:16
  • hmm yes the code doesn't seem as readable I have now got dr.IsNull("someString") ? "" :(string)dr["someString"] which seems a lot less readable compared to "" + dr["someString"] which I'm tempted to go with unless its going to be bad for performance... I'm not really worried about performance because this is not going to loop or anything I was just curious. – Leigh Ciechanowski Mar 09 '12 at 12:29
2

Whats wrong with dr["someString"].ValueOrEmpty()?

As for your original question. The performance will not matter. I promise you that there are several other areas that can be optimized which gives a lot better performance gain.

Write the most readable code. And do not optimize until it's proven that you need to.

Update:

public static class StringExtensions
{
    public static string ValueOrEmpty(this object obj)
    {
        return obj == null ? "" : obj.ToString();
    }
}
kaj
  • 5,133
  • 2
  • 21
  • 18
jgauffin
  • 99,844
  • 45
  • 235
  • 372