Use Stringbuffer When Appending to Strings

In Java, Strings are immutable objects. This means that they cannot be modified in any way after they are created. When you attempt to modify a String object, you often end up doing much more work than you expected, or need to.

For example, here is a simple and common method of concatenating values together in Java:

 String aString = "";aString = aString+"a";aString = aString+"b";System.out.println(aString);


Because Strings are immutable, the old aString object has to be discarded and a new aString object created every time a new string is appended. In terms of both execution time and memory consumption, object creation can be one of the most costly types of operations in Java.

Compare that to the StringBuffer approach:

 StringBuffer aBuffer = new StringBuffer();aBuffer.append("a");aBuffer.append("b");System.out.println(aBuffer.toString());


By using a StringBuffer object, the appended strings are added directly to the internal byte array of the StringBuffer rather than causing a new String object to be allocated.

In general, if you find yourself appending values to a String more than once in the lifetime of the String object, using a StringBuffer to manage your changing values can improve the speed and efficiency of your Java code.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS