A phone number consists of a few digits, perhaps a plus sign, and occasionally an extension. What’s so slow about that? With this reassuring question, you can put off launching a profiler for a surprisingly long time.
My telephone library processes national and international phone numbers as well as number ranges. The formatter architecture is based on an older Java formatter implementation: A pattern is first broken down into small parser and formatting modules, which then work together to get the job done. This is flexible, easy to understand, and, for starters, a good foundation.
But even with a proven architecture, it’s worth taking a closer look. So when I checked the runtime and memory usage, I took a closer look. The result: a few avoidable allocations, three parser errors, and a new major version. So “I’ll just tidy things up a bit” turned into a small software project. We’ve all been there.
First Accurate, Then Fast
Before I could save memory, I had to train the parser to stop being so lenient. These three cases were reproducible:
| Pattern | Input | Past Behavior |
|---|---|---|
+ccc nnn sss[-eee] | +49 30 123junk | The number was read; the rest was ignored. |
+ccc nnn sss[-eee] | +49 A0 B23 | A0 and B23 were accepted as part numbers. |
+ccc nnn sss[-eee-] | +49 30 123-45 | The optional section failed, but extension 45 remained in the results anyway. |
The first error was a lack of consistency: After iterating through the pattern, I didn’t check whether the entire input had been processed. The second was a classic “off-by-one” error: The digit loop didn’t start checking until the second character. As a result, the first character remained unchecked.
The third error was more subtle. An optional section reset the input position upon failure, but not the fields that had already been written. As a result, an extension number, for example, remained in the output even though the corresponding section had not been read in its entirety.
In version 2.0.0, the following now applies:
- The entire input must match the pattern. Remaining text, including unintended spaces, results in an IllegalArgumentException.
- Numeric parts must begin with a digit. This also applies to explicit block boundaries.
- Failed optional sections restore the position and field state, even in cases of nesting and overwritten values.
This affects phone number and block parsers. Inputs that were previously accepted may now fail; others will return corrected results. Therefore bekommt die Änderung eine neue Hauptversion und nicht bloß eine besonders selbstbewusste Patchnummer.
I first ran the new error tests against the old code. As expected, they failed. After making the corrections, they passed. That’s how I like regression tests: They reveal the error and then verify that it has been fixed.
Fewer temporary objects and duplicate data
The first optimization was minor and, thankfully, unspectacular. When comparing localized prefixes, I generated a substring to then determine whether it contained, for example, 00.
value.contentEquals(sequence.subSequence(pos, pos + value.length()))
With a string input, this meant a temporary string object along with a character buffer. Now I compare the characters directly in the input. No separate string is needed to compare an international dialing code like 00.
In addition, each formatter stored its compiled pattern as both a list and an array. The array was the one that was actually processed; the list was mainly there just to exist. Now I store the pattern building blocks exclusively in arrays, even within optional sections. Locale variants share the compiled structure and retain only their own localization values.
Parsing and Formatting: Separate Tasks
Parsing and formatting originally used the same context with a parts array. During parsing, this array served as a workspace. During formatting, however, it merely copied references from an existing phone number.
I have separated these tasks. The formatting context now accesses the immutable phone numbers and blocks directly. The temporary parts array is no longer needed; internal access to optional values no longer requires optional wrappers. The public API remains unchanged.
For optional formatting sections, I also calculate a field mask during compilation. Instead of recursively checking which fields are missing on every call, a bitwise comparison with the existing fields suffices. Nine possible fields fit comfortably into an int.
Optional sections without additional security objects
The first correct method for undoing optional parsing sections used a copy of the entire parts array. This was simple and reliable, but typically took up 56 bytes per section. Even when the optional extension didn’t exist at all.
In the next step, I therefore switched the parsing context to explicit fields. A separate write mask describes which fields an optional section can modify. Only their previous values are saved in local variables and written back in case of failure. No additional backup arrays or snapshot objects are created.
The emphasis is on separate. A block pattern reads the block start and block end during formatting, but writes the block pattern field during parsing. It would have been nice to simply reuse the formatting mask. Nice, but wrong—to be precise. Additional tests therefore verify the rollback of all parsing fields, even across nested sections.
An optimization that JIT already supported
Previously, NationalPhoneNumber.parse() first generated an international number and then returned its national component. Now, both types of results share the same parsing logic, and the national path constructs its result directly.
That sounds like a definite improvement. The benchmark, however, was less impressed than I was:
| National Parsing | Direct Path | Along the International Results |
|---|---|---|
| No extension number | 17.55 ± 1.11 million calls/s; 184 bytes/call | 17.95 ± 0.23 million calls/s; 184 bytes/call |
| With an extension number | 15.73 ± 0.14 million calls/s; 232 bytes/call | 15.48 ± 0.12 million calls/s; 232 bytes/call |
These values come from another targeted comparison with version 2.0.0 on November 6, 2026. Without direct access, the confidence intervals overlap; with direct access, the direct path is about 1.6 percent faster in this run. This small advantage is not visible in the complete series; therefore, a consistent throughput advantage across both runs has not been demonstrated. The allocations are the same in both runs. The JIT already eliminates the discarded international wrapper in the comparison benchmark. So I simplified the code but did not achieve a proven runtime gain. That, too, is a result—just not one worthy of a headline with three exclamation points.
Use formatTo to write directly to the output buffer
If I’m going to append a formatted number to a larger block of text anyway, there’s no need to go through the extra step of using a separate result string. That’s why both formatters now offer formatTo(…, StringBuilder):
InternationalPhoneNumber number = InternationalPhoneNumber.of("49", "0", "30", "123");
PhoneNumberBlock block = PhoneNumberBlock.of(number, "00", "99");
StringBuilder builder = new StringBuilder(64);
builder.append("Phone: ");
PhoneNumberFormatter.INTERNATIONAL_DIN_5008.formatTo(number, builder);
builder.append("; Block: ");
PhoneNumberBlockFormatter.INTERNATIONAL_BLOCK.formatTo(block, builder);
// Phone: +49 30 123; Block: +49 30 123 00-99
String text = builder.toString();
The methods rely on existing content. For a new output, I can reset the buffer using setLength(0) and reuse it. The existing format() methods use the same output path and continue to return a string.
What was the result?
I ran the complete benchmark suites: first the current version 2.0.0, then release 1.7.0. The common benchmarks use the same inputs and formatters.
Measurements were taken using JMH 1.37 on OpenJDK 25.0.2: one thread, two JVM forks, three warm-up iterations of one second each, and five measurement iterations of two seconds each, with G1GC and the GC profiler. The JVM heap was set to 1 GiB in both cases (-Xms1g -Xmx1g). The runs were executed sequentially so that they would not take computing time away from one another. The throughput values are averages; ± denotes the half-width of the 99.9-percent confidence interval reported by JMH. Allocation is gc.alloc.rate.norm, rounded to whole bytes per call.
| Operation | Throughput1.7.0 | Throughput2.0.0 | Allocation1.7.0 → 2.0.0 |
|---|---|---|---|
| International DIN 5008 Formatting | 17,89 ± 0,16 Mio./s | 22,70 ± 0,24 Mio./s | 200 → 152 Byte |
| International DIN 5008 formatting with extension numbers | 15,84 ± 0,61 Mio./s | 19,46 ± 0,41 Mio./s | 208 → 160 Byte |
| National DIN 5008 Formatting | 21,50 ± 0,31 Mio./s | 26,34 ± 0,26 Mio./s | 200 → 152 Byte |
International dialing with +, without an extension | 15,44 ± 0,22 Mio./s | 15,87 ± 0,08 Mio./s | 280 → 256 Byte |
International dialing with +, including direct dialing | 12,00 ± 0,27 Mio./s | 12,23 ± 1,94 Mio./s | 328 → 304 Byte |
International dialing with 00, without direct dialingl | 13,35 ± 0,27 Mio./s | 14,83 ± 0,13 Mio./s | 328 → 256 Byte |
| National DIN 5008 Parsing with International Results | 16,78 ± 0,14 Mio./s | 17,01 ± 0,33 Mio./s | 280 → 208 Byte |
Compile pattern +ccc nnn sss[-eee] | 9,12 ± 0,88 Mio./s | 8,65 ± 0,45 Mio./s | 424 → 368 Byte |
In this test series, international formatting achieves approximately 27 percent higher throughput and requires 24 percent less memory allocation. National formatting increases throughput by approximately 23 percent, also with 24 percent less memory allocation. When parsing with 00, the average throughput increases by approximately 11 percent, while memory allocation decreases by approximately 22 percent. International parsing with and without an extension number achieves a throughput approximately 3 percent higher than version 1.7.0 and requires about 9 percent less allocation.
However, fewer allocations do not automatically mean faster performance: for international parsing with an extension number and for national parsing with an international result, the confidence intervals overlap; a runtime gain has not been demonstrated in these cases. For the pattern compilation shown, the average throughput is approximately 5 percent lower, again with overlapping confidence intervals. What is demonstrated there is an approximately 13 percent reduction in allocation. The new version is therefore more efficient, but not demonstrably faster on every path.
The comparison is particularly clear when writing to a reused buffer. Here, both variants were measured in the same benchmark series using the current implementation:
| Issue | format() and append() | formatTo() | Allocation: Before → After |
|---|---|---|---|
| Internationale DIN-5008-Nummer | 19,30 ± 0,73 Mio./s | 32,04 ± 0,79 Mio./s | 152 → 32 Byte |
Block mit Pattern +ccc nnn sss[ ZZZ] | 12,87 ± 0,10 Mio./s | 19,63 ± 0,27 Mio./s | 208 → 32 Byte |
That’s about 66 percent and 53 percent more throughput, respectively, in version 2.0.0; formatTo() is not yet available in 1.7.0. The measurement uses a reused destination buffer with a capacity of 128 characters and includes resetting it with setLength(0), but neither resizing it nor a final toString() call. Anyone who needs a string at the end must still pay the cost of creating it. formatTo() saves the intermediate string, not the final string creation.
Conclusion: Cleaner design, lower memory requirements
Telephone 2.0.0 processes input more consistently and requires fewer temporary objects. The formatters remain pattern-based; their workspaces and data structures are now better tailored to the specific task. The formatTo() method also provides an efficient way to handle composite output and reuse buffers.
The test suite now includes 180 passed test cases. It validates the parser corrections, localization, optional sections, direct national results, and buffer reuse.
For the migration, I primarily need to check inputs that previously relied on partial parsing or generously accepted number segments. I extract surrounding text before parsing; I explicitly remove unwanted spaces, provided the application allows it. Optional sections are either delivered in full or omitted.
My most important insight, however, isn’t a new API: first reproduce the errors, then fix them correctly, then measure. And if the JIT has long since handled a supposed optimization, it deserves the credit. Even if it doesn’t write a blog.