Public class stringtest implements clock { private int i = 0; public void teststring () { string str = new string (); int j = i; for (; i < j + 40000; i++) { str += string.valueof (i); } } public void teststringbuffer () { stringbuffer sb = new stringbuffer (); int j = i; for (; i < j + 40000; i++) { sb.append ( String.valueof (i)); } } public void teststringbuilder () { Stringbuilder sb = new stringbuilder (); int j = i; for (; i < j + 40000; i++) { sb.append (String.valueof (i)); } } public static void main (String[] args) { stringtest test = new stringtest (); test.stamp ("String", test::teststring); test.stamp ("StringBuffer", test:: Teststringbuffer); test.stamp ("StringBuilder", test:: Teststringbuilder); test.stamp ("String", test::testString) ; test.stamp ("StringBuffer", test::teststringbuffer); test.stamp ("StringBuilder", test::teststringbuilder); test.stamp ("String", test::teststring); test.stamp ("StringBuffer", test::teststringbuffer); test.stamp ("StringBuilder", test::teststringbuilder); }}
Briefly explain the test:
-
Environment, Mac OS 10.10.4, CPU 2.6 GHz Intel Core i5, Memory 8G;
-
Each test ran 40,000 times, timed, and recorded the results;
-
Run three times;
The result is:
It takes [110000000] nono seconds to process [string]it takes [5000000] nono seconds to process [Stringbuffer]it takes [50 00000] Nono seconds to process [stringbuilder]it takes [654000000] nono seconds to process [string]it takes [4000000] Nono Seconds to process [stringbuffer]it takes [3000000] nono seconds to process [stringbuilder]it takes [565000000] Nono Seco NDS to process [String]it takes [3000000] nono seconds to process [stringbuffer]it takes [3000000] nono seconds to process [StringBuilder]
As can be seen from this result,
-
As expected, the latter two are better than the first, 15 times times 20 times times the same way;
-
The latter two methods are more stable than the first one, and they are probably really fast, yet not to the unstable stage;
-
StringBuilder is very close to stringbuffer performance, slightly better.
The reason why StringBuilder and StringBuffer are tested here is because I remember the recommendation to use StringBuilder if not involved in concurrency, presumably because StringBuilder has no synchronization control;
Look at the source of StringBuilder and StringBuffer, it is true:
StringBuilder Append code:
@Overridepublic StringBuilder Append (String str) {super.append (str); return this;}
StringBuffer Append code:
@Overridepublic synchronized stringbuffer append (String str) {tostringcache = null; Super.append (str); return this;}
But in a method where there is no concurrency control, Java should be optimized to remove this lock. (Unfortunately I do not know how to test such a situation), so in most cases, the use of StringBuffer will not become a problem;
Java connection string in several ways