Posts

What's the fastest way to concatenate two Strings in Java?

Image
According to the Java specification ( and since the very first version of Java ), in the section "String Concatenation Operator +" it is said that : To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression So basically, using the + operator or StringBuilder.append for variables is basically the same. You can see that concat is faster than StringBuilder only when concatenating only 2 Strings See that when adding more and more Strings, the StringBuilder resulting time is increasing more slowly that using the concat Note that the difference will be more significant when the strings are very long  Output :  Source code is available at: StringConcatenationPerformance.java

String

In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation). A string is generally understood as a data type and is often implemented as an array data structure of bytes (or words) that stores a sequence of elements, typically characters, using some character encoding. A string may also denote more general arrays or other sequences (or list) data types and structures. Depending on programming language and precise data type used, a variable declared to be a string may either cause storage in memory to be statically allocated for a predetermined maximum length or employ dynamic allocation to allow it to hold a variable number of elements. When a string appears literally in the source code, it is known as a string literal or an anonymous string. In formal languages, which are used in mathematical logic...