1. for iterationCount = 5000, the StringBuilder method's time is always 0ms. StringBuffer method's time is sometimes 0, sometimes ~16 ms.

2. for iterationCount = 50000, the StringBuffer method's time is always 0ms. StringBuilder method's time is sometimes 0, sometimes ~16 ms.

Q1. Why should one method in either case yield 0 always(5000â†’StringBuilder , 50000â†’StringBuffer )?

Q2. Why, upon changing the iterationCount from 5000 to 50000 or vice-versa, the 0 ms elapse time method is changed?

The output on my "intel Core i5 XP" machine is as follows:

**Output**

47ms over 5000 iterations for "+"

15ms over 5000 iterations for String concat method

16ms over 5000 iterations for StringBuffer append method

0msover 5000 iterations for StringBuilder append method

47ms over 5000 iterations for "+"

31ms over 5000 iterations for String concat method

0ms over 5000 iterations for StringBuffer append method

0msover 5000 iterations for StringBuilder append method

47ms over 5000 iterations for "+"

16ms over 5000 iterations for String concat method

0ms over 5000 iterations for StringBuffer append method

0msover 5000 iterations for StringBuilder append method

47ms over 5000 iterations for "+"

15ms over 5000 iterations for String concat method

16ms over 5000 iterations for StringBuffer append method

0msover 5000 iterations for StringBuilder append method

7515ms over 50000 iterations for "+"

2938ms over 50000 iterations for String concat method

0msover 50000 iterations for StringBuffer append method

0ms over 50000 iterations for StringBuilder append method

7640ms over 50000 iterations for "+"

2985ms over 50000 iterations for String concat method

0msover 50000 iterations for StringBuffer append method

0ms over 50000 iterations for StringBuilder append method

7547ms over 50000 iterations for "+"

2969ms over 50000 iterations for String concat method

0msover 50000 iterations for StringBuffer append method

15ms over 50000 iterations for StringBuilder append method

7765ms over 50000 iterations for "+"

3000ms over 50000 iterations for String concat method

0msover 50000 iterations for StringBuffer append method

16ms over 50000 iterations for StringBuilder append method

The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory | www.TechAspire.blogspot.in

Use System.nanoTime

<edit>

the key point is that, if you use + or concat then each loop one new object is created (StringBuilder) . hence bit time required.

</edit>

Edit: With nanoTime(), I could get the time properly and see the time difference. It was < 0 ms for some which are posted as 0 here.

The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory | www.TechAspire.blogspot.in

It is sorta covered in the JavaRanch Style Guide. |