String Performance

Most string code is fast enough, and a handful of habits cause nearly all the slow cases. This page looks at what a String costs in memory and how compact strings halve it, counts the bytes each common operation allocates, shows how hash codes are cached, measures the usual hot-path mistakes against their fixes, and explains why naive timings mislead.

Contents

What a String costs

A String is two objects: the String itself and the byte array that holds its characters. On a 64-bit HotSpot JVM with compressed references, the String object has a 12-byte header, a reference to the array, a cached hash code, a one-byte coder that says how the bytes are encoded, and a flag, padded to 24 bytes. The array adds its own 16-byte header plus the character data, rounded up to a multiple of 8.

Since Java 9 (JEP 254, compact strings), the coder decides the data size. If every character fits in Latin-1, each character takes one byte; otherwise every character takes two, as UTF-16. Before Java 9 every string used two bytes per character, so compact strings roughly halved the memory of typical text.

Because strings are immutable, many operations can return the original object when nothing changes, and the JVM can share strings freely between threads. The costs that remain come from creating new strings: every concatenation, substring, split and String.format allocates, and allocation turns into garbage collection work later.

JVM features that make strings cheaper
FeatureSinceEffect
Cached hashCodeJava 1.0The hash is computed once per string object
Interned literals in the heapJava 7The string pool can be garbage collected; see intern()
G1 string deduplicationJava 8u20 (JEP 192)Equal strings share one array, with -XX:+UseStringDeduplication
Compact stringsJava 9 (JEP 254)One byte per character for Latin-1 text
Indified concatenationJava 9 (JEP 280)+ computes the exact size and fills one array
Hash of zero cachedJava 13Strings whose hash is 0 no longer recompute it

The measurements on this page were taken with JDK 21 on a 2-CPU Linux machine. Memory and allocation figures are stable; times are rough and vary from run to run.

Memory per string, with and without compact strings

The program keeps a million 20-character strings alive and divides the growth in heap use by the count. It runs twice: once with the default settings, and once with -XX:-CompactStrings, which restores the pre-Java 9 layout. One set of strings is pure Latin-1; the other starts with a euro sign, which is outside Latin-1.

Java
import java.util.ArrayList;
import java.util.List;

public class MemoryLayout {

    public static void main(String[] args) {
        System.out.println("CompactStrings on (default):");
        measure();
    }

    static void measure() {
        int n = 1000000;
        // 20 chars each: Latin-1 text, then text with one non-Latin-1 char (the euro sign)
        System.out.printf("  20-char Latin-1 strings:    %5.1f bytes each%n", perString(n, false));
        System.out.printf("  20-char strings with \u20AC: %5.1f bytes each%n", perString(n, true));
    }

    static double perString(int n, boolean euro) {
        List<String> keep = new ArrayList<>(n);
        long before = used();
        for (int i = 0; i < n; i++) {
            String digits = String.format("%019d", i);
            keep.add(euro ? "\u20AC" + digits : "E" + digits);
        }
        long after = used();
        if (keep.size() != n) {
            throw new AssertionError();
        }
        // Subtract the list's reference array: 4 bytes per element with compressed oops
        return (after - before - 4.0 * n) / n;
    }

    static long used() {
        Runtime rt = Runtime.getRuntime();
        for (int i = 0; i < 3; i++) {
            System.gc();
        }
        return rt.totalMemory() - rt.freeMemory();
    }
}
Java
public class CompactStringsOff {

    // Run with -XX:-CompactStrings: every string uses 2 bytes per char, as before Java 9
    public static void main(String[] args) {
        System.out.println("CompactStrings off (-XX:-CompactStrings):");
        MemoryLayout.measure();
    }
}

Output of the two runs (heap measurements are approximate):

Output
CompactStrings on (default):
  20-char Latin-1 strings:     60.4 bytes each
  20-char strings with €:  76.0 bytes each
Output
CompactStrings off (-XX:-CompactStrings):
  20-char Latin-1 strings:     76.6 bytes each
  20-char strings with €:  76.0 bytes each
  • With compact strings, a 20-character Latin-1 string used about 60 bytes: 24 for the String object and about 36 for a 16-byte array header plus 20 bytes of text. Only a third of the memory is the text itself.
  • A single euro sign switches the whole string to two bytes per character, about 76 bytes. Text in Greek, Cyrillic, Chinese or with emoji always uses the two-byte form.
  • With compact strings turned off, the Latin-1 strings also took about 76 bytes. For an application whose heap is mostly ASCII strings, such as JSON or log processing, compact strings save roughly a fifth to a third of string memory, more for longer strings.
  • The fixed overhead of about 40 bytes per string is why many small duplicate strings waste so much memory, and why interning or deduplication can pay off.

Bytes allocated by common operations

Speed problems with strings are usually allocation problems: every new string is work for the garbage collector. HotSpot can report the bytes a thread has allocated, so the program runs each operation 100,000 times after a warm-up and divides. The inputs are chosen so that some operations have nothing to do.

Java
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.function.Supplier;

public class Allocation {

    static final com.sun.management.ThreadMXBean THREADS =
        (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
    static Object sink;

    public static void main(String[] args) {
        String name = "order";
        int id = 12345;
        String lower = "content-type";
        String padded = "  value  ";

        report("name + \"-\" + id", () -> name + "-" + id);
        report("String.format(\"%s-%d\")", () -> String.format("%s-%d", name, id));
        report("StringBuilder, default size", () -> new StringBuilder().append(name).append('-')
            .append(id).toString());
        report("String.valueOf(id)", () -> String.valueOf(id));
        report("lower.toLowerCase(ROOT)", () -> lower.toLowerCase(Locale.ROOT));
        report("\"Content-Type\".toLowerCase", () -> "Content-Type".toLowerCase(Locale.ROOT));
        report("lower.strip()", lower::strip);
        report("padded.strip()", padded::strip);
        report("lower.substring(0, 7)", () -> lower.substring(0, 7));
        report("lower.substring(0)", () -> lower.substring(0));
        report("lower.replace('x', 'y')", () -> lower.replace('x', 'y'));
        report("lower.split(\"-\")", () -> lower.split("-"));
        report("lower.matches(\"[a-z-]+\")", () -> lower.matches("[a-z-]+"));
        report("lower.equalsIgnoreCase(...)", () -> lower.equalsIgnoreCase("CONTENT-TYPE"));
    }

    // Average bytes allocated by the current thread per call, after warm-up
    static void report(String label, Supplier<Object> op) {
        for (int i = 0; i < 20000; i++) {
            sink = op.get();
        }
        long tid = Thread.currentThread().threadId();
        int calls = 100000;
        long before = THREADS.getThreadAllocatedBytes(tid);
        for (int i = 0; i < calls; i++) {
            sink = op.get();
        }
        long bytes = THREADS.getThreadAllocatedBytes(tid) - before;
        System.out.printf("%-30s %6d bytes per call%n", label, Math.round((double) bytes / calls));
    }
}

Output:

Output
name + "-" + id                    56 bytes per call
String.format("%s-%d")            450 bytes per call
StringBuilder, default size       112 bytes per call
String.valueOf(id)                 48 bytes per call
lower.toLowerCase(ROOT)             0 bytes per call
"Content-Type".toLowerCase         56 bytes per call
lower.strip()                       0 bytes per call
padded.strip()                     48 bytes per call
lower.substring(0, 7)              48 bytes per call
lower.substring(0)                  0 bytes per call
lower.replace('x', 'y')             0 bytes per call
lower.split("-")                  232 bytes per call
lower.matches("[a-z-]+")         1078 bytes per call
lower.equalsIgnoreCase(...)         0 bytes per call
  • Concatenation allocated 56 bytes: exactly one 11-character string, object plus array. The StringBuilder version allocated twice that, because the builder and its 16-character buffer are garbage too, unless the JIT removes them.
  • String.format allocated about 456 bytes for the same result: a Formatter, a parsed list of specifiers and temporary strings. In a loop that runs millions of times, that difference shows up in GC logs.
  • Methods that find nothing to change return the same object and allocate nothing: toLowerCase on lowercase text, strip without surrounding whitespace, substring(0), and replace when the character is absent. So calling them defensively is cheap when the input is usually clean.
  • split allocated over 200 bytes for two parts: the array, the strings and a list used while splitting. String.matches allocated over 1 KB per call, because it compiles a new Pattern and creates a Matcher every time.
  • equalsIgnoreCase compares in place and allocates nothing, unlike lowercasing both sides.

Cached hash codes

Strings are the most common HashMap keys, so their hash codes are computed often. The program times hashCode on a 20 million character string twice, on two kinds of copy, and prints some hash values worth knowing.

Java
public class HashCaching {

    public static void main(String[] args) {
        // hashCode is computed once, then cached in the String object
        String big = "x".repeat(20000000);
        long t0 = System.nanoTime();
        int h1 = big.hashCode();
        long first = System.nanoTime() - t0;
        t0 = System.nanoTime();
        int h2 = big.hashCode();
        long second = System.nanoTime() - t0;
        System.out.printf("first hashCode: %.2f ms, second: %.4f ms, equal: %b%n",
            first / 1e6, second / 1e6, h1 == h2);

        // new String(String) copies the cached hash too; a string built another way does not
        String copy = new String(big);
        t0 = System.nanoTime();
        copy.hashCode();
        System.out.printf("new String(big).hashCode():         %.4f ms%n",
            (System.nanoTime() - t0) / 1e6);
        String rebuilt = new StringBuilder(big).toString();
        t0 = System.nanoTime();
        rebuilt.hashCode();
        System.out.printf("StringBuilder copy, first hashCode: %.2f ms%n",
            (System.nanoTime() - t0) / 1e6);

        // Some strings hash to 0; since Java 13 a flag caches that case too
        for (String s : new String[] {"", "f5a5a608", "Aa", "BB", "polygenelubricants"}) {
            System.out.printf("%-20s hashCode %d%n", "\"" + s + "\"", s.hashCode());
        }

        // The formula: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
        String word = "abc";
        int manual = 0;
        for (char c : word.toCharArray()) {
            manual = 31 * manual + c;
        }
        System.out.println("\"abc\": manual " + manual + ", hashCode " + word.hashCode());
    }
}

Output:

Output
first hashCode: 21.43 ms, second: 0.0018 ms, equal: true
new String(big).hashCode():         0.0044 ms
StringBuilder copy, first hashCode: 20.67 ms
""                   hashCode 0
"f5a5a608"           hashCode 0
"Aa"                 hashCode 2112
"BB"                 hashCode 2112
"polygenelubricants" hashCode -2147483648
"abc": manual 96354, hashCode 96354
  • The first call walks all 20 million characters and took about 20 ms. The second returned the value stored in the object's hash field in microseconds.
  • new String(big) copies the cached hash along with the reference to the same byte array, so its first call was also instant. A string built through a StringBuilder is a new object with no cached hash and paid the full cost again.
  • The empty string and f5a5a608 hash to 0. Before Java 13, a hash of 0 meant "not computed yet", so such strings recomputed it on every call; a separate flag now records that case.
  • Aa and BB collide, and polygenelubricants hashes to Integer.MIN_VALUE, which breaks code that takes Math.abs(hash) % n as a bucket index, because Math.abs of that value is still negative.
  • The hash is s[0]*31^(n-1) + ... + s[n-1] computed with int overflow, which the manual loop reproduces for abc.

How HashMap uses these values is explained on the HashMap internals page.

Common hot-path mistakes, measured

Four patterns account for most slow string code in practice. Each is timed against its fix over a million calls, keeping the best of three runs, and the last column is the ratio.

Java
import java.util.Locale;
import java.util.function.Supplier;
import java.util.regex.Pattern;

public class HotPathMistakes {

    static final Pattern DIGITS = Pattern.compile("\\d+");
    static final boolean DEBUG_ENABLED = false;
    static Object sink;

    public static void main(String[] args) {
        int n = 1000000;
        String header = "Content-Type";
        String text = "id 12345";
        String csv = "a,b,c,d";

        compare("case-insensitive compare", n,
            "toLowerCase().equals", () -> header.toLowerCase(Locale.ROOT).equals("content-type"),
            "equalsIgnoreCase", () -> header.equalsIgnoreCase("content-type"));
        compare("contains digits", n,
            "String.matches(\".*\\\\d+.*\")", () -> text.matches(".*\\d+.*"),
            "precompiled find()", () -> DIGITS.matcher(text).find());
        compare("first field of a CSV line", n,
            "split(\",\")[0]", () -> csv.split(",")[0],
            "substring(0, indexOf)", () -> csv.substring(0, csv.indexOf(',')));
        compare("disabled debug message", n,
            "eager concatenation", () -> debug("user " + header + " id " + text),
            "Supplier, built lazily", () -> debug(() -> "user " + header + " id " + text));
    }

    static Object debug(String message) {
        return DEBUG_ENABLED ? message : null;
    }

    static Object debug(Supplier<String> message) {
        return DEBUG_ENABLED ? message.get() : null;
    }

    static void compare(String title, int n, String slowName, Supplier<Object> slow,
            String fastName, Supplier<Object> fast) {
        long a = best(n, slow);
        long b = best(n, fast);
        System.out.printf("%s (%,d calls)%n  %-28s %6.1f ms%n  %-28s %6.1f ms   %.0fx%n",
            title, n, slowName, a / 1e6, fastName, b / 1e6, (double) a / b);
    }

    // Best of 3 runs
    static long best(int n, Supplier<Object> op) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            for (int i = 0; i < n; i++) {
                sink = op.get();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best;
    }
}

Output (rough comparison; ratios matter more than the milliseconds):

Output
case-insensitive compare (1,000,000 calls)
  toLowerCase().equals           22.7 ms
  equalsIgnoreCase               10.3 ms   2x
contains digits (1,000,000 calls)
  String.matches(".*\\d+.*")    165.1 ms
  precompiled find()             35.6 ms   5x
first field of a CSV line (1,000,000 calls)
  split(",")[0]                  72.1 ms
  substring(0, indexOf)          17.4 ms   4x
disabled debug message (1,000,000 calls)
  eager concatenation            11.5 ms
  Supplier, built lazily          2.0 ms   6x
  • Lowercasing to compare creates a new string on every call. equalsIgnoreCase compares in place and was two to three times faster across runs.
  • String.matches compiles its regex each time; a static final Pattern was three to five times faster. The regex page has more on this.
  • Taking the first field with split(",")[0] builds all four parts and an array to use one of them. indexOf plus substring was four to five times faster.
  • Building a debug message that is then thrown away is pure waste. Passing a Supplier, as java.util.logging and Log4j 2 allow, or using a parameterized message such as SLF4J's log.debug("user {}", user), builds the text only when the level is enabled.

Related measurements live on the topic pages: concatenation in loops on the StringBuilder page, formatting on the formatting page, and repeated substring on the substring page.

Why naive timings mislead

All the timings on these pages use the best of several runs, because the JVM changes the code while it runs. The program times exactly the same loop five times in a row.

Java
public class NaiveTiming {

    static int sink;

    public static void main(String[] args) {
        String s = "hello world";
        // The same loop timed five times: the first runs include interpreting and compiling
        for (int round = 1; round <= 5; round++) {
            long t0 = System.nanoTime();
            int total = 0;
            for (int i = 0; i < 2000000; i++) {
                total += s.indexOf('w', i & 3);
            }
            sink = total;
            System.out.printf("round %d: %6.2f ms%n", round, (System.nanoTime() - t0) / 1e6);
        }
    }
}

Output:

Output
round 1:  12.36 ms
round 2:  12.59 ms
round 3:   6.92 ms
round 4:   6.65 ms
round 5:   6.65 ms
  • The first two rounds were up to about twice as slow as the later ones. The JVM starts by interpreting the loop, then compiles it with the C1 compiler, and finally with the optimizing C2 compiler once it is known to be hot.
  • A single measurement of the first run would have made indexOf look about twice as expensive as it is. Comparing two approaches where one ran first and one second can reverse the conclusion.
  • The JIT can also remove work whose result is unused, inline small methods and eliminate allocations, so a benchmark that does not use its results can measure nothing. That is why the programs here store results in a field.

For decisions that matter, use JMH, which handles warm-up, forking and dead-code elimination; see the JMH page.

A checklist for fast string code

String performance rules
SituationDo this
Building text in a loopStringBuilder, not +=
One expression with a few values+; it is compiled efficiently
Formatting in a hot loopConcatenation instead of String.format
Same regex used repeatedlyA static final Pattern
Simple separator or prefix workindexOf, startsWith, substring instead of regex or split
Case-insensitive equalityequalsIgnoreCase or regionMatches(true, ...)
Log messagesParameterized or lazily built messages
Many duplicate long-lived stringsA map-based pool, intern(), or -XX:+UseStringDeduplication
Values from a small fixed setAn enum instead of strings
Judging a changeMeasure allocation and time with JMH, not a single run