Some (speed) performance tests summarizing the various options, not that it really matters #microoptimization (using a linqpad extension)
Options
void Main()
{
object objValue = null;
test(objValue);
string strValue = null;
test(strValue);
}
// Define other methods and classes here
void test(string value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
void test(object value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
Probably important to point out that Convert.ToString(...)
will retain a null string.
Results
Object
- nullcheck 1.00x 1221 ticks elapsed (0.1221 ms) [in 10K reps, 1.221E-05 ms per]
- coallesce 1.14x 1387 ticks elapsed (0.1387 ms) [in 10K reps, 1.387E-05 ms per]
- string + 1.16x 1415 ticks elapsed (0.1415 ms) [in 10K reps, 1.415E-05 ms per]
- str.Concat 1.16x 1420 ticks elapsed (0.142 ms) [in 10K reps, 1.42E-05 ms per]
- Convert 1.58x 1931 ticks elapsed (0.1931 ms) [in 10K reps, 1.931E-05 ms per]
- str.Format 5.45x 6655 ticks elapsed (0.6655 ms) [in 10K reps, 6.655E-05 ms per]
String
- nullcheck 1.00x 1190 ticks elapsed (0.119 ms) [in 10K reps, 1.19E-05 ms per]
- Convert 1.01x 1200 ticks elapsed (0.12 ms) [in 10K reps, 1.2E-05 ms per]
- string + 1.04x 1239 ticks elapsed (0.1239 ms) [in 10K reps, 1.239E-05 ms per]
- coallesce 1.20x 1423 ticks elapsed (0.1423 ms) [in 10K reps, 1.423E-05 ms per]
- str.Concat 4.57x 5444 ticks elapsed (0.5444 ms) [in 10K reps, 5.444E-05 ms per]
- str.Format 5.67x 6750 ticks elapsed (0.675 ms) [in 10K reps, 6.75E-05 ms per]