Which is better Convert.ToSting () or just concatenate with an empty string?

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

      

or

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

      

What are the performance implications of the above examples?

+3


source to share


2 answers


What about:

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

      

which avoids unnecessary concatenation, unnecessary virtual calling and avoids the risk of calling a method on a null reference. It is unclear what is in this context dr

; if it is a data reader ( IDataReader

etc.), you may need:



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

      

or in case DataTable

something related to DataRow.IsNull

.

+8


source


What's up with dr["someString"].ValueOrEmpty()

?

As for your original question. Execution doesn't matter. I promise you that there are several other areas that can be optimized, resulting in much better performance gains.

Write the most readable code. And don't optimize until you are sure what you need.



Update:

public static class StringExtensions
{
    public static string ValueOrEmpty(this object obj)
    {
        return obj == null ? "" : obj.ToString();
    }
}

      

+2


source







All Articles