Skip to content
Fix Code Error

String concatenation: concat() vs “+” operator

March 13, 2021 by Code Error
Posted By: shs

Assuming String a and b:

a += b
a = a.concat(b)

Under the hood, are they the same thing?

Here is concat decompiled as reference. I’d like to be able to decompile the + operator as well to see what that does.

public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}

Solution

No, not quite.

Firstly, there’s a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.

To look under the hood, write a simple class with a += b;

public class Concat {
    String cat(String a, String b) {
        a += b;
        return a;
    }
}

Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:

java.lang.String cat(java.lang.String, java.lang.String);
  Code:
   0:   new     #2; //class java/lang/StringBuilder
   3:   dup
   4:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   7:   aload_1
   8:   invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   11:  aload_2
   12:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   15:  invokevirtual   #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/    String;
   18:  astore_1
   19:  aload_1
   20:  areturn

So, a += b is the equivalent of

a = new StringBuilder()
    .append(a)
    .append(b)
    .toString();

The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.

The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.

Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.

Answered By: Tom Hawtin – tackline

Related Articles

  • Fastest way to iterate over all the chars in a String
  • no match for ‘operator
  • Vue.JS & Spring Boot - Redirect to homepage on 404
  • Callback functions in C++
  • What does this symbol mean in JavaScript?
  • How to filter a RecyclerView with a SearchView
  • problem with client server unix domain stream…
  • Adding gif image in an ImageView in android
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • Getting weird compilation error in defining a…
  • C threads corrupting each other
  • Knight's tour Problem - storing the valid moves then…
  • What is a NullReferenceException, and how do I fix it?
  • Javax.net.ssl.SSLHandshakeException:…
  • Reference — What does this symbol mean in PHP?
  • Can't find why this datetime test fails, in F#
  • How to format a phone number in a textfield
  • How do I "decompile" Java class files?
  • How to decompile a whole Jar file?
  • Undefined reference to 'vtable for ✘✘✘'
  • How to create ranges and synonym constants in C#?
  • error: strcpy was not declared in this scope
  • function.name returns empty string if the function…
  • Draw in Canvas by finger, Android
  • C++ OpenGL stb_image.h errors
  • LNK2019 símbolo externo public: bool __thiscall ……
  • How does PHP 'foreach' actually work?
  • Auto-fit TextView for Android
  • Baffling variadic templates exercise
  • Accessing a Shared File (UNC) From a Remote,…
  • Smart way to truncate long strings
  • Is there any possible way to loop strcmp function in…
  • How to get the real and total length of char * (char array)?
  • Is it possible to print a variable's type in standard C++?
  • What is The Rule of Three?
  • WAVE file unexpected behaviour
  • What's wrong with 'template int compare(char p1 [N],…
  • Item position in RecyclerView only changing when…
  • C Argument number to create PGM images
  • Encrypt and decrypt a string using simple Javascript…
  • Builder pattern without inner class
  • How to download and save an image in Android
  • Overriding .fetch() works with fake data, errors…
  • Getting infinite loop after entering 2 objects to…
  • What is an IndexOutOfRangeException /…
  • What's the best way to get the last element of an…
  • Efficient Algorithm for Bit Reversal (from…
  • easiest way to extract Oracle form xml format data
  • Decompile .smali files on an APK
  • What is the copy-and-swap idiom?
  • What is and how to fix…
  • Confused about the Visitor Design Pattern
  • How to decompile an APK or DEX file on Android platform?
  • What is move semantics?
  • C++ Custom Exception classes
  • What am I doing wrong in my C binary search code?…
  • How to fix Hibernate LazyInitializationException:…
  • How to iterate through a JSON response with nested…
  • binary search tree is not working properly, but the…
  • Why does C++ code for testing the Collatz conjecture…
  • Post request with many-to-many relation
  • COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?
  • I want to create a SQLite database like in the…
  • C++ undefined reference to defined function
  • How the int.TryParse actually works
  • Nested class: Calling child class properties in parent class
  • How to make Javascript font responsive?
  • #define macro for debug printing in C?
  • How to pass ArrayList of Objects from one to another…
  • Binding complex object to a component
  • Overloading operators in typedef structs (c++)
  • C++ error: expected class member or base class name…
  • How to compile C++ under Ubuntu Linux?
  • ValueError: invalid literal for int () with base 10
  • How to solve the problem in Javascript code to…
  • Stack array using pop() and push()
  • Replacing a 32-bit loop counter with 64-bit…
  • Error: invalid operands of types ‘const char [35]’…
  • Why does this core dumped error happen in my class?…
  • Seeking advice for Item system in RPG game (Java)
  • C++17 conditional (ternary) operator inconsistency…
  • How to get rid of SourceMapConcat build error in emberjs?
  • Dynamically update values of a chartjs chart
  • Implementation of user defined array on stack and/or…
  • C++ Switch statement to assign struct values
  • Drawing a simple line graph in Java
  • Getting "Abort trap 6" using memset()
  • How do I print out the contents of a vector?
  • recyclerview opens wrong item after filtering list…
  • How to implement an STL-style iterator and avoid…
  • How to pass 2D array (matrix) in a function in C?
  • How to print and sort list of sellers based on Bonus…
  • Is there an addHeaderView equivalent for RecyclerView?
  • How to unescape a Java string literal in Java?
  • C program that replace word in sentence to another word
  • Quickest way to convert a base 10 number to any base…
  • Dynamic SQL executed inside a stored procedure in a…
  • LINQ query to include the parent name in the child item
  • Validation failed for one or more entities. See…
  • String to byte array in php

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to print out all the elements of a List in Java?

Next Post:

How to style icon color, size, and shadow of Font Awesome Icons

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error