I. Overview
string Processing in Java we often use Java to provide three classes to provide manipulation of strings, String,stringbuffer,stringbuilder
String: fixed length
stringbuffer: Non-fixed long thread safety
Stringbuilder: Not fixed thread
unsafe
Second, performance PK
1. Create a super-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++) {s Tr=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. Adding operations to string constants
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 ("Stri Ng "); 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 Stringbuil Der (); Strbdr.append ("string"); Strbdr.append ("and"); Strbdr.append ("string"); Strbdr.append ("Append");} System.out.println ("StringBuilder time :" + (System.currenttimemillis ()-startstringbuilder);}}
:
Iii. Summary
Based on the above performance comparison, we conclude that stringbuffer and stringbulder behave much better than string when we build a super-large string, and that the performance of string constants is not an order of magnitude, but that strings behave more than StringBuffer and Stringbu Ilder's performance is due to the fact that creating a string class is less expensive than creating StringBuffer and StringBuilder, so the use of these three classes has a very good choice of which class to use for our specific business.
Java Primer to Mastery--basic string StringBuffer StringBuilder performance PK