Java performance optimization with string optimization

Source: Internet
Author: User

  1. String Object
    The string object is an important data type in Java, and in most cases we will use a string object. In fact, in the Java language, its designers also do a lot of string optimization work, these are the characteristics of string objects, they are:Non-denaturing,Constant Pool OptimizationAnd The final definition of the string class .

    1.1 invariance
    The state of a string object does not change after it has been created. Why this is also the Java Designer's optimization, in Java mode, there is a pattern called invariant mode, the understanding of children's shoes should also know the role of invariant mode: When an object is multi-threaded sharing, and is frequently accessed, you can omit synchronization and lock time, thereby improving performance. and the invariant of string can be generalized to invariant mode.

    1.2 Constant Pool optimization

    What does constant pool optimization mean? That is, when two string objects have the same value, they simply refer to the same copy in the constant pool. So when a string in the program appears frequently, this optimization technique can save a significant amount of memory space. For example:

     1  String s1 = "123" ;  2  String s2 = "123" ;  3  string s3 = new  String ("123" );      4  System.out.println (S1==S2); // true       5  System.out.println (S1==S3); // false     6  System.out.println (S1==s3.intern ()); // true  

    In the above code, S1 and S2 refer to the same address, so the fourth line prints the result is true, while S3 is only equal to S1,S2, but S3 is created by the new String ("123"), which re-opens up the memory space, because the referenced address is different, So line 5th prints out that the False;intern method returns a reference to the string object in the solid pool, so the last line prints true.


    Definition of 1.3 final
    The string class is decorated with final and it is not possible to have a subclass of string in the system, which is also due to system security considerations.

  2. Common optimization methods in string manipulation
    2.1 Split () method optimization
    In general, the split () method gives us a lot of convenience, but its performance is not very good. It is recommended that you use the indexof () and substring () methods in combination for custom splitting, which can significantly improve performance.

    The optimization method of 2.2 string steady-sum operation
    Example code:

    1String s = "";2 LongSbegintime =System.currenttimemillis ();3  for(inti = 0; I < 100000; i++) {4s+= "S";5 }6 LongSendtime =System.currenttimemillis ();7SYSTEM.OUT.PRINTLN ("s stitching 100,000 times s Time:" + (Sendtime-sbegintime) + "MS");8         9StringBuffer S1 =NewStringBuffer ();Ten LongS1begintime =System.currenttimemillis (); One  for(inti = 0; I < 100000; i++) { AS1.append ("s"); - } - LongS1endtime =System.currenttimemillis (); theSystem.out.println ("S1 stitching 100,000 times s Time:" + (S1endtime-s1begintime) + "MS"); -          -StringBuilder s2 =NewStringBuilder (); - LongS2begintime =System.currenttimemillis (); +  for(inti = 0; I < 100000; i++) { -S2.append ("s"); + } A LongS2endtime =System.currenttimemillis (); atSystem.out.println ("S2 stitching 100,000 times s Time:" + (S2endtime-s2begintime) + "MS");

    Results:

      

    As shown in the example above, using the + number stitching string, its efficiency is significantly lower, and the use of StringBuffer and StringBuilder of the Append () method for stitching, efficiency is the use of the + number splicing way hundred or even thousand times, The efficiency of StringBuffer is lower than that of StringBuilder, which is due to the fact that StringBuffer realizes thread safety and low efficiency is unavoidable. Therefore, in the summation of the string operation, it is recommended to combine threading problem selection, should avoid using the + number stitching string.

    The choice of 2.3 StringBuffer and StringBuilder
    The above example also used StringBuffer and StringBuilder, the two are only thread-safe differences, so, without regard to thread safety, it is recommended to use the relatively high performance of the StringBuilder class, if the system requires thread safety, Select the StringBuffer class.

    2.4 Optimization scheme for conversion of basic data types to string types
    Example code:
      

    1Integer num = 0;2 intloop = 100000;//enlarge the result 100,000 times times to make it easier to observe the results3 LongBeginTime =System.currenttimemillis ();4  for(inti = 0; I < loop; i++) {5String s = num+ "";6 }7 LongEndTime =System.currenttimemillis ();8System.out.println ("+\" \ "The Way Time:" + (Endtime-begintime) + "MS");9         Ten          OneBeginTime =System.currenttimemillis (); A  for(inti = 0; I < loop; i++) { -String s =string.valueof (num); - } theEndTime =System.currenttimemillis (); -System.out.println ("string.valueof () Time Consuming:" + (Endtime-begintime) + "MS"); -          -BeginTime =System.currenttimemillis (); +  for(inti = 0; I < loop; i++) { -String s =num.tostring (); + } AEndTime =System.currenttimemillis (); atSystem.out.println ("toString () takes time:" + (Endtime-begintime) + "MS");

    In the example above, string.valueof () calls the underlying integer.tostring () method directly, but it will be empty first, + "" is implemented by StringBuilder, the Append () method is called first, and then ToString () is called. The Num.tostring () method gets the string, and the Integer.tostring () method is called directly, so the efficiency is: the Num.tostring () method is the fastest, followed by string.valueof (num), and finally num+ "" way. Here are the results:
      

    It is advisable to avoid using the + "" conversion, preferably using the ToString () method that comes with the basic data type. Let's just share it here!!!

Java performance optimization with string optimization

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.