Comparison of StringBuilder emptying efficiency in Java

Source: Internet
Author: User

Know that if multiple strings are spliced, using stringbuilder.append will be much more efficient than str+= ""

Because you do not have to create string objects and array copies,

In jdk1.5, 3 methods were tested to clear the builder

Package Com.jb.efile.model;

Import java.io.IOException;
	public class Test {private static long;
		public static void Main (string[] args) throws IOException {StringBuilder builder = new StringBuilder ();
		Time = System.currenttimemillis ();
			for (int i=0;i<10000000;i++) {builder = new StringBuilder ();
			Builder.append ("AA");
			Builder.append ("BB");
			Builder.append ("CC");
			Builder.append ("DD");
		Builder.append ("ee");
		} System.out.println ("New Time Consuming:" + (System.currenttimemillis ()-time);
			for (int i=0;i<10000000;i++) {builder.delete (0, Builder.length ());
			Builder.append ("a");
			Builder.append ("B");
			Builder.append ("C");
			Builder.append ("D");
		Builder.append ("E");
		} System.out.println ("Delete time consuming:" + (System.currenttimemillis ()-time);
			for (int i=0;i<10000000;i++) {builder.setlength (0);
			Builder.append ("1a");
			Builder.append ("1b");
			Builder.append ("1c");
			Builder.append ("1d");
		Builder.append ("1e"); } System.out.println ("Setlenth=0 time Consuming: "+ (System.currenttimemillis ()-time);"
 }
}
Output:

New time consuming: 1146
Delete time consuming: 2268
setlenth=0 time consuming: 3371

So I test new efficiency will be high, but a lot of people on the Internet test said delete efficiency, I hope you copy the code to their own environment in the test under the parents

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.