J
Jeroen Mostert
Well, I thought we were talking about the general case of turning anPeter said:I wouldn't suggest using StringBuilder in this case anyway. You've got
a finite well-defined string length to deal with and I doubt there's a
significant performance difference between the two. Just appending
String instances eight times is probably fine, even though it does
result in a much larger number of data copies.
arbitrary array of bytes into a string. Sure, if you're limited to eight
bytes exactly, then you don't need a loop to begin with. But then my point
also vanishes.
I disagree that there's anything wrong with using some sort of
formatting in a loop here.
The point is that String.Format() is expensive compared to other string
operations. In most cases, it's a cost you'll want to pay, because being
able to write
String.Format("There's {0} foozits out of {1} remaining with an average
processing time of {2} per item", remaining, total, averageTime);
is a lot more convenient and readable than doing the same with
concatenation. Especially when you combine this with locale-specific
formatting, precision modifiers and last but certainly not least localization.
And if you're doing *that* in a loop, then it's probably because it's
exactly what you need to do, and avoiding it won't buy you anything but
missed deadlines and angry customers.
That's why I'd never suggest something like that as a general rule, it'sRules like "don't format strings in loops" just leads to
difficult-to-read code (C programmers notwithstanding). It's not a
good rule, because there are so many good exceptions to it.
like saying "don't use useful things because they don't work for free", and
nothing is ever for free. And, sure, the usual caveats about "don't optimize
(yet)" apply. But a programmer should be able to understand and explain why
calling StringBuilder.AppendFormat() to repeatedly string two hex digits
together is a potentially inefficient solution, even if it's not a
bottleneck in practice (that is, it's not *too* inefficient so it doesn't
matter).
And this *particular* problem (assuming we're going back to the general case
of arbitrarily long arrays) happens to be better solved with BitConverter,
not only because it's faster, but because it absolves you from writing the
actual code! Reuse and less potential for errors, what's not to like? Hence
the "if it's obvious to avoid" clause.