Java beginners-basics-String StringBuffer StringBuilder performance PK, stringbuffer
I. Overview
In java, we often use java to provide three classes for String operations: String, StringBuffer, and StringBuilder.
String: Fixed Length
StringBuffer: unfixed long thread security
Stringbuilder: unfixed and long threads are not secure
Ii. Performance PK
1. Create a large string.
Code:
public class StringOne {public static void main(String[] args) {String str="";StringBuffer strb=new StringBuffer();StringBuilder strbd=new StringBuilder();long startString=System.currentTimeMillis();for (int i = 0; i < 100000; i++) {str=str+i;}System.out.println("String add Time:"+(System.currentTimeMillis()-startString));long startStringBuffer=System.currentTimeMillis();for (int i = 0; i < 100000; i++) {strb.append(i);}System.out.println("StringBuffer add Time:"+(System.currentTimeMillis()-startStringBuffer));long startStringBuilder=System.currentTimeMillis();for (int i = 0; i < 100000; i++) {strbd.append(i);}System.out.println("StringBuilder add Time:"+(System.currentTimeMillis()-startStringBuilder));}}
:
2. Add a String constant
Code:
public class StringTwo {public static void main(String[] args) {long startString=System.currentTimeMillis();for (int i = 0; i < 100000000; i++) {String str="String"+"and"+"String"+"append";}System.out.println("String Time:"+(System.currentTimeMillis()-startString));long startStringBuffer=System.currentTimeMillis();for (int i = 0; i < 100000000; i++) {StringBuffer strb=new StringBuffer();strb.append("String");strb.append("and");strb.append("String");strb.append("append");}System.out.println("StringBuffer Time:"+(System.currentTimeMillis()-startStringBuffer));long startStringBuilder=System.currentTimeMillis();for (int i = 0; i < 100000000; i++) {StringBuilder strbdr=new StringBuilder();strbdr.append("String");strbdr.append("and");strbdr.append("String");strbdr.append("append");}System.out.println("StringBuilder Time:"+(System.currentTimeMillis()-startStringBuilder));}}
:
Iii. Summary
Through the comparison of the above performance, it is concluded that the StringBuffer and StringBulder performance is much better than the String performance when we build a super-large String, but it is not an order of magnitude in the String constant addition operation. the performance is better than that of StringBuffer and StringBuilder, the reason is that it takes less time to create a String class than to create StringBuffer and StringBuilder. Therefore, the usage of these three classes varies depending on our specific business.