Use of string concatenation strings and StringBuilder (StringBuffer) in Java

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.