Everyone has expressed their opinions, maybe I should too! ;-)

Although I have great respect for Mahesh Chand, I think that that
particular article is only for newbies. Using DateTime.Now().ToString
() is hardly a good way to evaluate time elapsed. Additionally, such
measurements should be in ticks, seconds are too large a unit to
detect minute performance differences that only show up over hundreds
of thousands of iterations. Thirdly, performance is usually gauged as
an average time over a number of test repetitions. (Say, you run the
code 20 times and calculate the average time taken)

Finally, I always prefer to use the StringBuilder any time I am
concatenating more than 5 strings. When using the StringBuilder, I try
to guess an appropriate capacity(usually half or slightly more than
estimated total capacity) for the object and use the overload that
accepts a starting size. For instance,

---
// "example" has 7 characters, so 7 x 20 will be 140 chars. Since this
is a small number, I'll use 150 (round figure).
// Now the StringBuilder will not need to double its buffer at all.
StringBuilder sb = new StringBuilder(150)
for (int i = 0; i < 20; i++)
{
  sb.Append("example");
}
---

Note that I am not saying that this code is noticeably faster than
concatenating 20 instances of a string. I only intend to demonstrate
the *best* way to use a StringBuilder. Since the default initial
capacity is only 16, it means that the StringBuilder would have to
reallocate buffers atleast 4 times to suffice for a 140 char capacity.
(16+32+64+128)

Hope that clears up any persisting doubts.

--
Cerebrus.

On Feb 5, 1:19 pm, Brandon Betances <[email protected]> wrote:
> http://www.c-sharpcorner.com/UploadFile/mahesh/StringBuilderComp11232...
>
> It's obvious he's not concatenating more than 10 strings. The proof is in
> the muri.

Reply via email to