String concatenation is a common function, often using string concatenation, when the number of stitching, using the string method will consume a lot of performance and time, because each string splicing will create a new object, with the increase in splicing times, performance consumption, The time consuming will increase a lot, this time should use the StringBuilder method.
1 Public Static voidMain (string[] args) {2 Try {3 intCount = -;4 5 LongBegin =System.currenttimemillis ();6 teststring (count);7 LongEnd =System.currenttimemillis ();8 LongTime = end-begin;9System. out. println ("String Method Stitching"+count+"Times Consumed:"+ Time +"milliseconds");Ten OneBegin =System.currenttimemillis (); A Teststringbuilder (count); -End =System.currenttimemillis (); -Time = end-begin; theSystem. out. println ("StringBuilder Method Stitching"+count+"Times Consumed:"+ Time +"milliseconds"); - -}Catch(Exception e) { - e.printstacktrace (); + } - + } A at Private StaticString teststring (intcount) { -String result =""; - - for(inti =0; I < count; i++) { -Result + ="Hello"; - } in - returnresult; to } + - Private StaticString Teststringbuilder (intcount) { theStringBuilder SB =NewStringBuilder (); * $ for(inti =0; I < count; i++) {Panax NotoginsengSb.append ("Hello"); - } the + returnsb.tostring (); A}
Operation Result:
String method Splicing 500 times Elapsed time: 2 ms StringBuilder method Stitching 500 times Elapsed time: 0 ms
String method Splicing 50,000 times elapsed time: 4973 ms StringBuilder method Stitching 50,000 times Elapsed time: 3 ms
Use of string concatenation strings and StringBuilder (StringBuffer) in Java