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 StringStringString
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, substringsplitString.format
| Feature | Since | Effect |
|---|---|---|
Cached hashCode | Java 1.0 | The hash is computed once per string object |
| Interned literals in the heap | Java 7 | The string pool can be garbage collected; see |
| G1 string deduplication | Java 8u20 (JEP 192) | Equal strings share one array, with -XX:+UseStringDeduplication |
| Compact strings | Java 9 (JEP 254) | One byte per character for Latin-1 text |
| Indified concatenation | Java 9 (JEP 280) | + |
| Hash of zero cached | Java 13 | Strings 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
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();
}
}
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):
CompactStrings on (default):
20-char Latin-1 strings: 60.4 bytes each
20-char strings with €: 76.0 bytes each
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
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.String - 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.
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:
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
version allocated twice that, because the builder and its 16-character buffer are garbage too, unless the JIT removes them.StringBuilder allocated about 456 bytes for the same result: aString.format , a parsed list of specifiers and temporary strings. In a loop that runs millions of times, that difference shows up in GC logs.Formatter- Methods that find nothing to change return the same object and allocate nothing:
on lowercase text,toLowerCase without surrounding whitespace,strip , andsubstring(0) when the character is absent. So calling them defensively is cheap when the input is usually clean.replace allocated over 200 bytes for two parts: the array, the strings and a list used while splitting.split allocated over 1 KB per call, because it compiles a newString.matches and creates aPattern every time.Matcher compares in place and allocates nothing, unlike lowercasing both sides.equalsIgnoreCase
Cached hash codes
Strings are the most common HashMaphashCode
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:
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
field in microseconds.hash copies the cached hash along with the reference to the same byte array, so its first call was also instant. A string built through anew String(big) is a new object with no cached hash and paid the full cost again.StringBuilder- The empty string and
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.f5a5a608 andAa collide, andBB hashes topolygenelubricants , which breaks code that takesInteger.MIN_VALUE as a bucket index, becauseMath.abs(hash) % n of that value is still negative.Math.abs- The hash is
computed withs[0]*31^(n-1) + ... + s[n-1] overflow, which the manual loop reproduces forint .abc
How HashMap
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.
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):
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.
compares in place and was two to three times faster across runs.equalsIgnoreCase compiles its regex each time; aString.matches was three to five times faster. Thestatic final Patternregex page has more on this.- Taking the first field with
builds all four parts and an array to use one of them.split(",")[0] plusindexOf was four to five times faster.substring - Building a debug message that is then thrown away is pure waste. Passing a
, asSupplier and Log4j 2 allow, or using a parameterized message such as SLF4J'sjava.util.logging , builds the text only when the level is enabled.log.debug("user {}", user)
Related measurements live on the topic pages: concatenation in loops on the substring
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.
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:
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
look about twice as expensive as it is. Comparing two approaches where one ran first and one second can reverse the conclusion.indexOf - 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
A checklist for fast string code
| Situation | Do this |
|---|---|
| Building text in a loop | StringBuilder+= |
| One expression with a few values | + |
| Formatting in a hot loop | Concatenation instead of String.format |
| Same regex used repeatedly | A static final Pattern |
| Simple separator or prefix work | indexOfstartsWithsubstringsplit |
| Case-insensitive equality | equalsIgnoreCaseregionMatches(true, ...) |
| Log messages | Parameterized or lazily built messages |
| Many duplicate long-lived strings | A map-based pool, intern()-XX:+UseStringDeduplication |
| Values from a small fixed set | An enum |
| Judging a change | Measure allocation and time with JMH, not a single run |