Reputation: 137
What's the absolute fastest way to format a full name? where the middlename and suffix might be null or empty?
string fullname = string.Format("{0} {1} {2} {3}",
FName,
MI,
LName,
Suffix);
The problem with this is that if the MI or suffix is empty, then I have two spaces.
I could make a second pass with this:
fullname = fullname.Replace(" ", " ");
or I could just make the string with something like this:
string fullname = string.Format("{0}{1} {2}{3}",
FName,
string.IsNullOrEmpty(MI) ? "" : " " + MI,
LName,
string.IsNullOrEmpty(Suffix) ? "" : " " + Suffix);
Is there a better option? Fastest is the important thing.
Upvotes: 2
Views: 1177
Reputation: 269378
I would do this:
var parts = new[] { FName, MI, LName, Suffix };
string fullName = string.Join(" ", parts.Where(s => !string.IsNullOrWhiteSpace(s)));
It's probably not the fastest solution, but it makes it pretty clear what's going on.
Upvotes: 4
Reputation: 108800
Check first for null-or-empty and then write specialized code for each of them. I'd expect directly working on a char[]
buffer to be faster than string.Format
or StringBuilder.
But I find it strange that formatting names is a performance bottleneck in your application. Even formatting a few million names shouldn't take that long.
Upvotes: 1