首页 > 其他分享 >Performance improvement techniques in String and StringBuffer

Performance improvement techniques in String and StringBuffer

时间:2023-08-01 17:02:24浏览次数:50  
标签:String StringBuffer object new objects time Performance techniques


This topic illustrates the performance improvement techniques in String and StringBuffer with the following sections:

Overview of String and StringBuffer

Immutable objects cannot be modified once they are created. Mutable objects can be modified after their creation. String objects are immutable where as StringBuffer objects are mutable. 
You need to carefully choose between these two objects depending on the situation for better performance. The following topics illustrate in detail :

Note: This section assumes that reader has some basic knowledge of Java Strings and StringBuffer.

Better way of creating Strings

You can create String objects in the following ways.

1.String s1 = "hello";
String s2 = "hello";
2.String s3 = new String("hello");
String s4 = new String("hello");

Which of the above gives better performance?

Here is a code snippet to measure the difference.

StringTest1.java

 

 

 

The output of this code

 

 

 

 

It clearly shows first type of creation is much more faster than second type of creation. Why?

Because the content is same s1 and s2 refer to the same object where as s3 and s4 do not refer to the same object. The 'new' key word creates new objects for s3 and s4 which is expensive.

 

How the JVM works with Strings:

Java Virtual Machine maintains an internal list of references for interned Strings ( pool of unique Strings) to avoid duplicate String objects in heap memory. Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it  does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object which it creates through 'new' keyword. You can explicitly force JVM to do this type of checking for String objects which are created through 'new' keyword using String.intern() method. This forces JVM to check the internal list and use the existing String object if it is already present.

So the conclusion is, JVM maintains unique String objects for String literals internally. Programmers need not bother about String literals but they should bother about String objects that are created using 'new' keyword and they should use intern() method to avoid duplicate String objects in heap memory which in turn improves java performance. see the following section for more information.

The following figure shows the creation of String Objects without using the intern() method.


You can test the above difference programmatically using == operator and String.equals() method.

== operator returns true if the references point to the same object but it does not check the contents of the String object where as String.equals() method returns true if the contents of the String objects are equal.

s1==s2 for the above code returns true because s1 and s2 references point to the same object.

s3.equals(s4) for the above code returns true because both objects content  is same which is "hello".

You can see this mechanism in the above figure. Here, we have three separate objects which contain same content,"hello". Actually we don't need separate objects because they use memory and take time to execute.

How do you make sure that the String objects are not duplicated?

The next topic covers this interesting interning String mechanism.

 

Optimization by Interning Stings

In situations where String objects are duplicated unnecessarily, String.intern() method avoids duplicating String objects. The following figure shows how the String.intern() method works. The String.intern() method checks the object existence and if the object exists already, it changes point of reference to the original object rather than create a new object.

The following figure shows the creation of String literal and String Object using intern

 

Here is the sample code to know the importance of String.intern() method..

StringTest2.java

 

 

 

Here is the output of the above code

 

 

 


Optimization techniques when Concatenating Strings


You can concatenate multiple strings using either + operator or String.concat()  or   StringBuffer.append(). Which is the best one interms of performance?


The choice depends on two scenarios,first scenario is compile time resolution versus run time resolution and second scenario is wether you are using StringBuffer or String. In general, programmers think that StringBuffer.append() is better than + operator or String.concat() method. But this assumption is not true under certain conditions.


1) First scenario: compile time resolution versus run time resolution


Look at the following code StringTest3.java and the output.


 


 



 


 


The output of this code

 

 

 


 


Interestingly the + operator is faster than StringBuffer.append() method. Let us see why?


Here the compiler does a good job of optimization. Compiler simply concatenates at compile time as shown below. It does compile time resolution instead of runtime resolution, this happens when you create a String object using 'new' key word.


before compilation:


String result = "This is"+"testing the"+"difference"+"between"+"String"+"and"+"StringBuffer";


after compilation


String result = "This is testing the difference between String and StringBuffer";


String object is resolved at compile time where as StringBuffer object is resolved at run time. Run time resolution takes place when the value of the string is not known in advance where as compile time resolution happens when the value of the string is known in advance. Here is an example.


Before compilation:


public String getString(String str1,String str2) {


            return str1+str2;


}


After compilation:


return new StringBuffer().append(str1).append(str2).toString();


This resolves at run time and take much more time to execute.


 


2) Second scenario: Using StringBuffer instead of String


If you look at the following code, you will find StringBuffer is faster than String for concatenation which is opposite to above scenario.


StringTest4.java


 



 


 


the output of the code is


 



It shows StringBuffer.append() is much more faster than String. Why?


The reason is both resolve at runtime but the + operator resolves in a different manner and uses String and StringBuffer to do this operation.


 


Optimization by initializing StringBuffer


You can set the initial capacity of StringBuffer using its constructor this improves performance significantly. The constructor is StringBuffer(int length), length shows the number of characters the StringBuffer can hold.


You can even set the capacity using ensureCapacity(int minimumcapacity) after creation of StringBuffer object. Initially we will look at the default behavior and then the better approach later.


The default behavior of StringBuffer:


StringBuffer maintains a character array internally.When you create StringBuffer with default constructor StringBuffer() without setting initial length, then the StringBuffer is initialized with 16 characters. The default capacity is 16 characters. When the StringBuffer reaches its maximum capacity, it will increase its size by twice the size plus 2 ( 2*old size +2).


 If you use default size, initially and go on adding characters, then it increases its size by 34(2*16 +2) after it adds 16th character and it increases its size by 70(2*34+2) after it adds 34th character. Whenever it reaches its maximum capacity it has to create a new character array and recopy old and new characters. It is obviously expensive. So it is always good to initialize with proper size that gives very good performance.


I tested the above StringTest4.java again with two StringBuffers, one without initial size and other with initial size. I added 50000 'hello' objects this time and did not use the + operator. I initialized the second StringBuffer with StringBuffer(250000).


The output is 


 



 


 


It shows how effective the initialization of StringBuffer is. So it is always best to initialize the StringBuffer with proper size.


 


Key Points

package com.performance.string;/** This class shows the time taken for creation of String literals and String objects.*/public class StringTest1 {public static void main(String[] args){          // create String literals          long startTime = System.currentTimeMillis();          for(int i=0;i<50000;i++){          String s1 = "hello";          String s2 = "hello";          }          long endTime = System.currentTimeMillis();          System.out.println("Time taken for creation of String literals : "                                          + (endTime - startTime) + " milli seconds" );           // create String objects using 'new' keyword                 long startTime1 = System.currentTimeMillis();          for(int i=0;i<50000;i++){          String s3 = new String("hello");          String s4 = new String("hello");          }          long endTime1 = System.currentTimeMillis();          System.out.println("Time taken for creation of String objects : "                                          + (endTime1 - startTime1)+" milli seconds");         }}

 

 

 

 


标签:String,StringBuffer,object,new,objects,time,Performance,techniques
From: https://blog.51cto.com/u_6174294/6924553

相关文章

  • Java之String系列--String, StringBuffer, StringBuilder区别
    简介本文介绍Java的String,StringBuffer,StringBuilder的区别。项StringStringBufferStringBuffer线程安全性不可变。原因:value数组是final类型。因为不可变,所以每次操作生成新对象。因为不可变,所以每次操作生成新对象。原因:value数组是final类型。原因:其父类(AbstractStringBuilder......
  • Quantitative Approach of Management Science:(better decision making by using qua
    Whichistheuseofquantitativetechniquestoimprovemanagerialdecisionmaking.Alsoknownasmanagementscience.Bettermanagerialdecisionmakingbyusingquantitativetechniques,suchas:Thequantitativeapproachevolvedfrommathematicalandstati......
  • 【后端面经-Java】String与StringBuffer与StringBuilder的比较
    目录1.String2.StringBuffer3.StringBuilder4.性能提升5.总结和比较面试模拟参考资料1.String不可变查看String源码如下:publicfinalclassStringimplementsjava.io.Serializable,Comparable<String>,CharSequence{/**Thevalueisusedforcharacterstora......
  • Delta Lake_ High-Performance ACID Table Storage over Cloud Object Stores
    论文发表于2020年,研究数据湖产品的很好的学习资料.概要开篇很明确的表明了为什么要做Deltalake这样一个产品.Databricks尝试将数据仓库直接架在云上对象存储之上,这种尝试的过程中遇到了对象存储的一些问题,为了解决这些问题,提出了Deltalake这套技术方案.对象存储的......
  • String、StringBuffer、StringBuilder 的区别?
    一.介绍String、StringBuffer、StringBuilder:  前言: String、StringBuffer、StringBuilder均在java.lang包下;String: 在Java中,String是一个特殊的引用类型,用于表示文本字符串。它提供了许多方法来操作和处理字符串,比如连接、截取、查找、替换等。String类......
  • Jmeter学习之五_跟踪被测试服务器的performance
    Jmeter学习之五_跟踪被测试服务器的performance背景这几天简单学习了一些基本的测试过程.可以实现一些简单基本的功能了.今天晚上继续进行了jmeter的一些学习.想着可以在测试人大金仓的同时可以查看一下本地的机器性能.用到的工具以及资料https://www.cnblogs.com/......
  • Java 基础复习——StringBuffer 和 StringBuilder
    StringBuffer和StringBuilderStringBuffer类简介java.lang.StringBuffer代表可变的字符序列,可以对字符串内容进行增删很多方法和String相同,但StringBuffer是可变长度的StringBuffer是一个容器注意:StringBuffer的直接父类是AbstractStringBuilder有属......
  • 11.performance_schema_01
    1.Mysql的performance_schema是运行在较低级别的用于监控mysqlserver运行过程中资源消耗、资源等待的一个功能。2.查看当前是否支持root@mysqldb21:14:[performance_schema]>showengines;+--------------------+---------+--------------------------------------------......
  • MYSQL 8 上云 performance_schema 里面参数我们打开了那些 5个表调整脚本?(POLARDB
    关于监控如果上云后,到底还需要自行进行监控吗,是一个问题,是否把所有的数据库监控都放到云上,通过云来获取数据库的信息是一个问题。首先回答是否定的,1  云的数据库监控的数据,部分也是通过数据库中的系统的表中获得的2 云的监控数据的需要进行处理加工,处理加工的方式对不对,这也是......
  • MYSQL 从performance_schema说起,但不止于PS (1)
    以下的内容,希望你的环节是在8.011以上的环境中操作,部分需要在8.018以上环境操作MYSQL如果你在使用MYSQL8的版本,那么performanceschema的确的重新认识一下了。在重新认识mysql的performance_schema之前我们有一些需要在强化的知识。分别是threads,instruments,consume......