In the case of 2 lines, the performance differences are slight, but try the following:
String s = ""; for( int i = 0; i < 10000; i++ ) { s += i; }
vs.
StringBuilder b = new StringBuilder(); for( int i = 0; i < 10000; i++ ) { b.append(i); }
You will find that the second cycle is faster. What for? Because string concatenation will create a new String object at each iteration, which takes up processor cycles as well as memory.
I will give you:
To write a test test of good comparisons, you need to test it several thousand (million) times. It will influence the influence of other programs (in most cases).
The same applies to tests in one virtual machine: check your code several times, use big data, big loops, etc. Comparison of only small parts does not make sense due to errors in the accuracy of time and other influences (for example, garbage collection working between them). A.
source share