String concatenation in a single shot will be faster than using a StringBuilder
- although if Sb
is already a StringBuilder
, it might make sense to append to that instead (assuming it's a local variable). Assuming this is actually data which has come from a database, the time taken to fetch it is going to vastly exceed the string concatenation here anyway.
Note that you don't need all these calls to ToString()
- this would do just as well:
return (Sb + " " + ds.Tables[1].Rows[0].ItemArray[0] + " " +
ds.Tables[2].Rows[0].ItemArray[0]);
Here's the equivalent using the existing builder:
return Sb.Append(" ")
.Append(ds.Tables[1].Rows[0].ItemArray[0])
.Append(" ")
.Append(ds.Tables[2].Rows[0].ItemArray[0])
.ToString();
This might be slightly faster - it will depend on various things. Personally I'd probably use the concatenation version anyway, as it's slightly simpler IMO. I highly doubt that you'd see much difference in performance. Note that this is a bit of a special case, as you've already got a StringBuilder
; in the general case of concatenating a set of items where they can all be specified in one compile-time expression, concatenation can be faster as a single method call can provide all the required information.
I have a page on StringBuilder
vs string concatenation if you want more details and guidelines.