Roman Numerals: the Uncle Bob Way (and how to avoid it)
An example in the latest (2nd.) edition of Uncle Bob’s book “Clean Code” made my bad-performance bell ring.
Intro
I brought the 2nd edition (printed 2026 at least here in Germany) of the book “Clean Code” from Robert C. Martin (aka “Uncle Bob”) from my latest trip to the local library.
The book is split into parts, and in the first chapter of part 1 (Code) he describes his hopefully well-known ideas of Clean Code, and I generally agree. As a programmer I take pride in writing good code, and although I think that my ideas of good code and Bob’s ideas of clean code don’t always agree, they don’t differ too much.
But in the second chapter he introduces an example where he writes code to parse Roman numerals. And that is, where thinks start to become worse.
Sorry: This is becoming a long post, so there are several parts. But on the way there are a few performance hints which you might find useful.
And thanks to this article from The Axolot I didn’t have to copy much of the code by hand. A readable article, and Uncle Bob even joins the discussion.
Bob, if you ever read this: why is your code not in some repository in the web?
Part 1
Hopefully you know how Modern Roman Numerals are constructed, otherwise ask Wikipedia: Roman numerals.
His first try is this:
public class FromRoman {
public static int convert(String roman) {
if (roman.contains("VIV") ||
roman.contains("IVI") ||
roman.contains("IXI") ||
roman.contains("LXL") ||
roman.contains("XLX") ||
roman.contains("XCX") ||
roman.contains("DCD") ||
roman.contains("CDC") ||
roman.contains("MCM")) { // this is wrong, it should be "CMC"
throw new InvalidRomanNumeralException(roman);
}
roman = roman.replace("IV", "4");
roman = roman.replace("IX", "9");
roman = roman.replace("XL", "F");
roman = roman.replace("XC", "N");
roman = roman.replace("CD", "G");
roman = roman.replace("CM", "O");
if (roman.contains("IIII") ||
roman.contains("VV") ||
roman.contains("XXXX") ||
roman.contains("LL") ||
roman.contains("CCCC") ||
roman.contains("DD") ||
roman.contains("MMMM")) {
throw new InvalidRomanNumeralException(roman);
}
int[] numbers = new int[roman.length()];
int i = 0;
for (char digit : roman.toCharArray()) {
switch (digit) {
case 'I' -> numbers[i] = 1;
case 'V' -> numbers[i] = 5;
case 'X' -> numbers[i] = 10;
case 'L' -> numbers[i] = 50;
case 'C' -> numbers[i] = 100;
case 'D' -> numbers[i] = 500;
case 'M' -> numbers[i] = 1000;
case '4' -> numbers[i] = 4;
case '9' -> numbers[i] = 9;
case 'F' -> numbers[i] = 40;
case 'N' -> numbers[i] = 90;
case 'G' -> numbers[i] = 400;
case 'O' -> numbers[i] = 900;
default -> throw new InvalidRomanNumeralException(roman);
}
i++;
}
int lastDigit = 1000;
for (int number : numbers) {
if (number > lastDigit) {
throw new InvalidRomanNumeralException(roman);
}
lastDigit = number;
}
return Arrays.stream(numbers).sum();
}
public static class InvalidRomanNumeralException extends RuntimeException {
public InvalidRomanNumeralException(String roman) {
}
}
He probably implemented this using his test-first principle, at least it looks like it when I see all these
roman.contains() calls. Bob writes himself that this code is deliberately unclean, so he has a base for improvement.
The basic ideas are quite clear (see the Axolot blog post where he explains
this step by step). But as a side note: the code is incorrect, it excludes MCM in the first if which is a valid
Roman numeral (1900). Probably a copy error, meant is CMC which is indeed invalid.
All these repeated calls to the String methods contains() and replace() are ugly, and quite
inefficient as they go over roman again and again. As I consider efficiency a valuable goal (saves time and energy),
I usually keep it in my mind as a part of good programming, and can smell inefficiency quite well.
You’ll see comparisons of the speed of the various approaches later on.
After Bob’s refactoring the code looks like this:
public class FromRoman2 {
private String roman;
private List<Integer> numbers = new ArrayList<>();
private int charIx;
private char nextChar;
private Integer nextValue;
private Integer value;
private int nchars;
Map<Character, Integer> values = Map.of(
'I', 1,
'V', 5,
'X', 10,
'L', 50,
'C', 100,
'D', 500,
'M', 1000);
public FromRoman2(String roman) {
this.roman = roman;
}
public static int convert(String roman) {
return new FromRoman2(roman).doConversion();
}
private int doConversion() {
checkInitialSyntax();
convertLettersToNumbers();
checkNumbersInDecreasingOrder();
return numbers.stream().reduce(0, Integer::sum);
}
private void checkInitialSyntax() {
checkForIllegalPrefixCombinations();
checkForImproperRepetitions();
}
private void checkForIllegalPrefixCombinations() {
checkForIllegalPatterns(
new String[]{"VIV", "IVI", "IXI", "IXV", "LXL", "XLX",
"XCX", "XCL", "DCD", "CDC", "CMC", "CMD"});
}
private void checkForImproperRepetitions() {
checkForIllegalPatterns(
new String[]{"IIII", "VV", "XXXX", "LL", "CCCC", "DD", "MMMM"});
}
private void checkForIllegalPatterns(String[] patterns) {
for (String badString : patterns)
if (roman.contains(badString)) throw new InvalidRomanNumeralException(roman);
}
private void convertLettersToNumbers() {
char[] chars = roman.toCharArray();
nchars = chars.length;
for (charIx = 0; charIx < nchars; charIx++) {
nextChar = isLastChar() ? 0 : chars[charIx + 1];
nextValue = values.get(nextChar);
char thisChar = chars[charIx];
value = values.get(thisChar);
switch (thisChar) {
case 'I' -> addValueConsideringPrefix('V', 'X');
case 'X' -> addValueConsideringPrefix('L', 'C');
case 'C' -> addValueConsideringPrefix('D', 'M');
case 'V', 'L', 'D', 'M' -> numbers.add(value);
default -> throw new InvalidRomanNumeralException(roman);
}
}
}
private boolean isLastChar() {
return charIx + 1 == nchars;
}
private void addValueConsideringPrefix(char p1, char p2) {
if (nextChar == p1 || nextChar == p2) {
numbers.add(nextValue - value);
charIx++;
} else
numbers.add(value);
}
private void checkNumbersInDecreasingOrder() {
for (int i = 0; i < numbers.size() - 1; i++)
if (numbers.get(i) < numbers.get(i + 1))
throw new InvalidRomanNumeralException(roman);
}
public static class InvalidRomanNumeralException extends RuntimeException {
public InvalidRomanNumeralException(String roman) {
super("Invalid Roman numeral: " + roman);
}
}
}
Similar to The Axolot I don’t think this code is improved. Creating an object for keeping the state divides the algorithm from its variables, so you have to jump around in the code to understand it.
It is at least a lot more efficient, as it does not use String.replace() multiple times.
But the contains() still remain.
Here’s a timing measurement where I parse all valid Roman numerals a 1000 times on my machine
(it also contains the measurement for the alternative path of improving the original code found there as Roman3
in The Axolot’s blog post):
| Algorithm | Duration (ms) |
|---|---|
| Bob’s first try | 3768 |
| Bob’s refactoring | 922 |
| Axolot’s refactoring | 1004 |
In the German edition of Bob’s book there is another iteration of his code, which is shorted and a bit cleaner, but still uses an unnecessary object with fields instead of static methods with arguments and return values. I’m to lazy to copy that by hand, so it’s missing here.
Part 2: In Comes AI
Bob embraces modern technology, and let’s Grok 3 improve his refactored code. I had to copy this by hand, but at least it’s quite short, and I ported it back to Java 8 thanks to some of my customers still stuck with it.
public class RomanNumeralsGrok
{
@NotNull
private final String roman;
private static final String REGEX = "^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
private static final Map<Character, Integer> VALUES = new HashMap<Character, Integer>();
static {
VALUES.put('M', 1000);
VALUES.put('D', 500);
VALUES.put('C', 100);
VALUES.put('L', 50);
VALUES.put('X', 10);
VALUES.put('V', 5);
VALUES.put('I', 1);
}
public RomanNumeralsGrok(@NotNull String roman)
{
if (!roman.matches(REGEX)) {
throw new InvalidRomanNumeralException(roman);
}
this.roman = roman;
}
public int toInt()
{
int sum = 0;
for (int i = 0; i < roman.length(); i++) {
int currentValue = VALUES.get(this.roman.charAt(i));
if (i < roman.length() - 1) {
int nextValue = VALUES.get(this.roman.charAt(i + 1));
if (currentValue < nextValue) {
sum -= currentValue;
}
else {
sum += currentValue;
}
}
else {
sum += currentValue;
}
}
return sum;
}
public static int convert(@NotNull String roman)
{
return new RomanNumeralsGrok(roman).toInt();
}
}
Of course this is not a refactoring, but a rewrite. Grok just pasted some code it found in its memory. Though it kept the unnecessary wrapping, which is completely useless here. At least the code is quite clear.
The check for invalid Roman numerals is now condensed in a failed match of a regular expression. It’s a standard one for Roman numerals, see e.g. this article on StackOverflow.
But I saw at first glance that this code is awfully inefficient for no good reason. Here’s the result of what I did to the code in 2 minutes time:
public class RomanNumeralsGrokImproved
{
private static final String REGEX = "^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
private static final Pattern PATTERN = Pattern.compile(REGEX);
private static final Map<Character, Integer> VALUES = new HashMap<Character, Integer>();
static {
VALUES.put('M', 1000);
VALUES.put('D', 500);
VALUES.put('C', 100);
VALUES.put('L', 50);
VALUES.put('X', 10);
VALUES.put('V', 5);
VALUES.put('I', 1);
}
public static int convert(@NotNull String roman)
{
if (!PATTERN.matcher(roman).matches()) {
throw new InvalidRomanNumeralException(roman);
}
int sum = 0;
int lastValue = 0;
for (int i = roman.length() - 1; i >= 0; --i) {
final int currentValue = VALUES.get(roman.charAt(i));
if (currentValue < lastValue) {
sum -= currentValue;
}
else {
sum += currentValue;
}
lastValue = currentValue;
}
return sum;
}
}
There’s mainly 3 things I changed:
- I introduced the
PATTERNconstant. - I removed the unnecessary wrapping of the
Stringromanin a class, and used only static methods. - I inverted the scan direction and kept the last value in
lastValue. This makes the method much shorter, and more efficient:
roman.length()is only called once, and each map access only happens once per letter.
So the code is shorter, but is it faster? Let’s see the results:
| Algorithm | Duration (ms) |
|---|---|
| Bob’s first try | 3768 |
| Bob’s refactoring | 922 |
| Axolot’s refactoring | 1004 |
| Grok’s rewrite | 2741 |
| Grok’s rewrite, improved | 638 |
So I was right, Grok’s rewrite was slow, and my simple improvements made it run some 4 times faster.
The reason for the bad performance is the usage of the String.matches() convenience method.
Internally it will compile the regexp into a Pattern. On each call. Over and over again.
And that compilation is an expensive operation.
So if you take anything away from this blog post, whether you are human or AI:
Never ever use Java’s java.lang.String.matches() method in code unless you are sure the
regular expression argument is used only once in the complete lifetime of your program!
Or shorter:
Don’t use java.lang.String.matches()! Use a java.util.Pattern instead.
And the same is basically true for the String.split(), although split patterns are usually much shorter.
So the AI code is quite okay. But I still wasn’t convinced.
Part 3: Understand What You Do
I’m usually slow at the beginning of a project, because I need time to understand what I plan to implement. Usually I become faster using my insights later on. Therefore, I consider this slow time at the beginning a good thing. And at least understanding Roman numerals is perfectly simple.
But be warned that the code I’ll introduce now will be a bit longer, as it uses a lot of building blocks. Each one is simple IMHO, and they play nicely together, but you need a bit of understanding. So at the end I’ll show a perfectly simple and fast way how you should parse Roman numerals in the real world. To give a bit of motivation here is the table with the final timings:
| Algorithm | Duration (ms) |
|---|---|
| Bob’s first try | 3768 |
| Bob’s refactoring | 922 |
| Axolot’s refactoring | 1004 |
| Grok’s rewrite | 2741 |
| Grok’s rewrite, improved | 638 |
| Rammi w/ understanding | 287 |
| Code for the real world | 29 |
Yes, parsing 4 Million Roman numerals can be done in 29 ms if you really need this. And have 6 ms time.
Understanding Roman Numerals
Old Roman numerals (see Wikipedia) without the digraphs would be basically very simple to parse: make sure the symbols appear in order, count each symbol and take care that some may appear up to four times and some only once.
The basic digits with their symbols in their expected order looks like:
| Digit | Value | # Appearances |
|---|---|---|
| M | 1000 | 0 to 3 |
| D | 500 | 0 or 1 |
| C | 100 | 0 to 3 |
| L | 50 | 0 or 1 |
| X | 10 | 0 to 3 |
| V | 5 | 0 or 1 |
| I | 1 | 0 to 3 |
You can spot a pairing structure with the digit pairs I/V, X/L, C/D (first digit can appear thrice, the second only once) and the special value M (a half-pair?).
Digraphs are created by prepending the first digit of these pairs to the two digits above:
| Symbol | Value | # Appearances |
|---|---|---|
| M | 1000 | 0 to 3 |
| CM | 900 | 0 or 1 |
| D | 500 | 0 or 1 |
| CD | 400 | 0 or 1 |
| C | 100 | 0 to 3 |
| XC | 90 | 0 or 1 |
| L | 50 | 0 or 1 |
| XL | 40 | 0 or 1 |
| X | 10 | 0 to 3 |
| IX | 9 | 0 or 1 |
| V | 5 | 0 or 1 |
| IV | 4 | 0 or 1 |
| I | 1 | 0 to 3 |
The pair structure became groups of 4 symbols for each the units, the decimals, and the hundreds. M is special, again.
Usually when parsing we can go down to the next row in the table. This will always work for the symbols which may appear thrice, and for symbols which don’t appear.
But for symbols which may appear only once we have to skip further when we encounter them.
| Symbol | Value | # Appearances | Next if appearing | Delta |
|---|---|---|---|---|
| M | 1000 | 0 to 3 | CM | +1 |
| CM | 900 | 0 or 1 | XC | +4 |
| D | 500 | 0 or 1 | C | +2 |
| CD | 400 | 0 or 1 | XC | +2 |
| C | 100 | 0 to 3 | XC | +1 |
| XC | 90 | 0 or 1 | IX | +4 |
| L | 50 | 0 or 1 | X | +2 |
| XL | 40 | 0 or 1 | IX | +2 |
| X | 10 | 0 to 3 | IX | +1 |
| IX | 9 | 0 or 1 | none | +4 |
| V | 5 | 0 or 1 | I | +2 |
| IV | 4 | 0 or 1 | none | +2 |
| I | 1 | 0 to 3 | none | +1 |
| none | 0 | n.a. | n.a. | n.a. |
The skipping values in the last column follow the repeated 4-memnber-sequence +1, +4, +2, +2.
Algorithm
Using the above table we will build a parser which will go over the possible values starting with the largest, and count the appearance of the symbol.
The inner loop looks like:
- If the symbol does not appear, repeat with the next symbol (i.e. the next row of the table above).
- If the symbol does appear too often, throw an error.
- Otherwise, add the value times the number of appearances.
Finally, if all symbols are used up, but we still have something left, that’s also an error.
The main advantage here is, that we don’t need an extra check like the regular expression: the checking is already part of the left-to-right parsing of the incoming text string.
Building Blocks
The building blocks are inner classes/interfaces of an outer class called RomanNumeralsRammi.
We start with the basic Symbols (either a digit or a digraph).
/** A symbol in a Roman numeral. */
public interface Symbol
{
/**
* Get the representation of this symbol.
* @return representation of this symbol
*/
@NotNull
String getRepresentation();
/**
* Get the value of this symbol.
* @return value of this symbol
*/
int getValue();
/**
* Get the length of this symbol.
* @return length of this symbol in letters, either {@code 1} or {@code 2}
*/
int length();
/**
* Count how many times this symbol appears at the start of the given Roman numeral.
* @param romanNumeral roman numeral
* @return number of appearances at the start of the given Roman numeral
* @throws NumberFormatException if this symbol appears too often
*/
int countLeft(@NotNull String romanNumeral);
/**
* Get the next possible symbol if this symbol appears at the start of the given Roman numeral.
* @return next symbol if this symbol appears at the start of the given Roman numeral,
* {@code null} if no other symbols can follow
*/
@Nullable
Symbol getNextIfAppearing();
/**
* Get the next possible symbol if this symbol does not appear at the start of the given Roman numeral.
* @return next symbol if this symbol doesn't appear at the start of the given Roman numeral,
* {@code null} if no other symbols can follow
*/
@Nullable
Symbol getNextIfNotAppearing();
/**
* Append this symbol to the given builder if the given value allows this.
* Return the remainder.
* @param builder builder to append to
* @param value value to represent
* @return remainder of value after the possibly multiple appearance of this symbol was appended
*/
int appendIfAppropriate(@NotNull StringBuilder builder, int value);
}
The javadoc should tell enough.
The interface is designed this way to make the parsing simple (see next code block) .
The appendIfAppropriate() method helps to convert an integer to a Roman numeral (a cheap extension).
Here’s how a Roman numeral is parsed:
/**
* Parse the given Roman numeral.
* @param romanNumber Roman numeral to parse
* @return parsed value
* @throws NumberFormatException if the given Roman numeral is invalid
*/
public static int parse(@NotNull String romanNumber) throws NumberFormatException
{
try {
Symbol symbol = Digit.LARGEST; // 1.
int result = 0;
String remaining = romanNumber;
while (symbol != null) { // 2.
final int count = symbol.countLeft(remaining); // 3.
if (count == 0) {
symbol = symbol.getNextIfNotAppearing(); // 4.
} else {
result += symbol.getValue() * count; // 5.i
remaining = remaining.substring(symbol.length() * count); // 5.ii
symbol = symbol.getNextIfAppearing(); // 5.iii
}
}
if (!remaining.isEmpty()) {
throw new NumberFormatException("Invalid suffix of roman number: " + remaining);
}
return result;
} catch (NumberFormatException x) {
// include original number in message
throw prepareInvalidFormatException(romanNumber, x);
}
}
That’s the algorithm from above (plus a bit of error handling):
- Start with the largest symbol.
- As long as we have symbols left:
- Count how many appear at the start of the remaining text. Throws if too many.
- If symbol does not appear: use the next symbol (row below in the table).
- If symbol does appear:
- Add to result.
- Cut away symbol’s appearances to get the remaining text.
- Possibly skip symbols which can no longer appear.
The purpose of the outer try-catch block is to provide a nicer exception message which contains the original input, while the cause exception gives a better hint what went wrong.
Now we need to create the symbols. Here’s the digits (the digraphs will be constructed automatically from this):
/** Roman digits. */
public enum Digit implements Plumbing
{
M(1000),
D(500),
C(100),
L(50),
X(10),
V(5),
I(1);
/**
* The values of this enum.
* Use this instead of {@link #values()} because it does not require internal array copying.
*/
@NotNull
public static final Indexable<Digit> VALUES = Indexable.viewArray(values()).frozen();
/** The largest digit. */
@NotNull
public static final Digit LARGEST = VALUES.foldLeft(I, (acc, digit) -> acc.getValue() > digit.getValue() ? acc : digit);
public final char letter;
public final int value;
public final int maxCount;
private Symbol nextIfAppearing;
private Symbol nextIfNotAppearing;
Digit(int value)
{
letter = name().charAt(0);
this.value = value;
maxCount = ordinal() % 2 == 0
? 3
: 1;
}
@NotNull
@Override
public String getRepresentation()
{
return name();
}
@Override
public int getValue()
{
return value;
}
@Override
public int length()
{
return 1;
}
@Override
public int countLeft(@NotNull String romanNumeral)
{
final int len = romanNumeral.length();
int count = 0;
while (count < len && romanNumeral.charAt(count) == letter) {
++count;
if (count > maxCount) {
throw new NumberFormatException("Too many repetitions of " + letter + ": " + romanNumeral);
}
}
return count;
}
@Nullable
@Override
public Symbol getNextIfAppearing()
{
return nextIfAppearing;
}
@Nullable
@Override
public Symbol getNextIfNotAppearing()
{
return nextIfNotAppearing;
}
@Override
public void setNextIfAppearing(@NotNull Symbol nextIfAppearing)
{
this.nextIfAppearing = nextIfAppearing;
}
@Override
public void setNextIfNotAppearing(@NotNull Symbol nextIfNotAppearing)
{
this.nextIfNotAppearing = nextIfNotAppearing;
}
@Override
public int appendIfAppropriate(@NotNull StringBuilder builder, int value)
{
int count = 0;
while (value >= this.value) {
if (++count > maxCount) {
throw new IllegalArgumentException("Number too large for a Roman numeral: " + (value + (count - 1) * this.value));
}
value -= this.value;
builder.append(letter);
}
return value;
}
}
It uses the Indexable class from my de.caff commons: think of it as a read-only
list/array which is inherently immutable and communicates this to the programmer and the compiler,
which differs it from an unmodifiable List where incorrect usage will result in a runtime errors.
Most properties like the multiplicity can be calculated, so the only real property of the enum values is their numeric value.
You might notice that the wiring is missing. That is done during the loading of the outer class (RomanNumeralsRammi)
and described below. And that wiring is the reason that Digit does not implement Symbol but Plumbing:
/** Helper interface only used during wiring up the symbols. */
private interface Plumbing extends Symbol
{
void setNextIfAppearing(@NotNull Symbol nextIfAppearing);
void setNextIfNotAppearing(@NotNull Symbol nextIfNotAppearing);
}
The digraphs also have a straight-forward implementation:
/** A combination of two Roman digits, such as IV or IX. */
private static class Digraph implements Plumbing
{
private final int value;
@NotNull
private final String representation;
@Nullable
private Symbol nextIfAppearing;
@Nullable
private Symbol nextIfNotAppearing;
Digraph(@NotNull Digit minus, @NotNull Digit plus)
{
value = plus.value - minus.value;
representation = minus.getRepresentation() + plus.getRepresentation();
}
@NotNull
@Override
public String getRepresentation()
{
return representation;
}
@Override
public int getValue()
{
return value;
}
@Override
public int length()
{
return 2;
}
@Override
public int countLeft(@NotNull String romanNumeral)
{
return romanNumeral.startsWith(representation)
? 1
: 0;
}
@Nullable
@Override
public Symbol getNextIfAppearing()
{
return nextIfAppearing;
}
@Nullable
@Override
public Symbol getNextIfNotAppearing()
{
return nextIfNotAppearing;
}
@Override
public int appendIfAppropriate(@NotNull StringBuilder builder, int value)
{
if (value >= this.value) {
value -= this.value;
if (value >= this.value) {
throw new IllegalArgumentException("Number too large for Roman numerals: " + (value + this.value));
}
builder.append(representation);
}
return value;
}
@Override
public void setNextIfAppearing(@NotNull Symbol nextIfAppearing)
{
this.nextIfAppearing = nextIfAppearing;
}
@Override
public void setNextIfNotAppearing(@NotNull Symbol nextIfNotAppearing)
{
this.nextIfNotAppearing = nextIfNotAppearing;
}
@Override
public String toString()
{
return representation;
}
}
And here’s how the wiring up of the Symbols works, implemented as a static initializer of RomanNumeralsRammi.
static {
final List<Plumbing> symbols = new ArrayList<>(2 * Digit.VALUES.size() - 1);
Digit.VALUES.addAllTo(symbols);
// create the digraphs
for (int i = 2; i < Digit.VALUES.size(); i += 2) {
final Digit minus = Digit.VALUES.get(i);
final Digit back1 = Digit.VALUES.get(i - 1);
final Digit back2 = Digit.VALUES.get(i - 2);
symbols.add(new Digraph(minus, back2));
symbols.add(new Digraph(minus, back1));
}
// sort digits and digraphs by value, largest first
symbols.sort(Comparator.comparingInt(Symbol::getValue).reversed());
assert Digit.LARGEST == symbols.get(0);
// perform plumbing: when not appearing use next symbol,
// otherwise apply the repeated following 4-fold pattern of deltas
final IntIndexable deltaIfAppearing = IntIndexable.viewArray(1, 4, 2, 2);
final int numSymbols = symbols.size();
for (int i = 0; i < numSymbols - 1; ++i) {
final Plumbing symbol = symbols.get(i);
final int nextAppearing = i + deltaIfAppearing.getMod(i);
if (nextAppearing < numSymbols) {
symbol.setNextIfAppearing(symbols.get(nextAppearing));
}
symbol.setNextIfNotAppearing(symbols.get(i + 1));
}
}
It uses IntIndexable, which is the same as Indexable, but for primitive int values.
Think of a read-only int[] array with some useful convenience methods like getMod() doing a modulo access.
I agree that this is complex, although each of the building blocks is basically simple and straight-forward. After understanding the problem, writing down the code wasn’t difficult, and indeed the first version was already running all tests green.
It uses much more code than the improved Grok product. It runs twice as fast. And the complete code (see Downloads section at the end of this post) also contains the inverse conversion: numbers to Roman Numerals. This will come quite handy soon.
The reason that it is faster, is because Pattern matching is also slow. As said, the pattern matching in the Grok code is
used to create errors for invalid numerals. If we completely remove it the improved Grok code is some 20 times faster
(just 33ms compare to the 638ms in the table above). Of course, it will return 999 for IM.
Real World
But if you ever have a real world project where you have to create or parse a lot of Roman numerals use this:
/**
* This class is useful if you have to parse or create a lot of 'modern' Roman numerals.
* <ul>
* <li>Parse Roman numerals with {@link #parse(String)}.</li>
* <li>Create Roman numerals with {@link #toRoman(int)}.</li>
* </ul>
* <p>
* The price for its fastness is that it uses some 10MB of memory,
* and needs a few milliseconds time for initialization (measured 6ms, but YMMV).
*
* @author <a href="mailto:rammi@caff.de">Rammi</a>
* @since November 22, 2026
*/
public class RomanNumerals
{
/** Maximum Roman numeral value supported. */
public static final int MAX_ROMAN = 3999;
private static final String[] ROMAN_NUMERALS_BY_VALUE = new String[MAX_ROMAN + 1];
private static final Map<String, Integer> VALUES_BY_ROMAN_NUMERAL = new HashMap<>(MAX_ROMAN + 1);
static {
final StringBuilder sb = new StringBuilder();
for (int n = MAX_ROMAN; n >= 0; --n) {
final String roman = Symbol.toRoman(n, sb);
ROMAN_NUMERALS_BY_VALUE[n] = roman;
VALUES_BY_ROMAN_NUMERAL.put(roman, n);
}
}
/** Don't create. */
private RomanNumerals() {}
/**
* Parses a Roman numeral into an integer.
*
* @param romanNumeral the Roman numeral to parse
* @return the integer value of the Roman numeral
* @throws NumberFormatException if the Roman numeral is invalid
*/
public static int parse(String romanNumeral)
throws NumberFormatException
{
final Integer value = VALUES_BY_ROMAN_NUMERAL.get(romanNumeral);
if (value == null) {
throw new NumberFormatException("Invalid Roman numeral: " + romanNumeral);
}
return value;
}
/**
* Converts an integer to a Roman numeral.
*
* @param value the integer value to convert, has to be non-negative and less than or equal to the maximum Roman numeral value ({@value #MAX_ROMAN})
* @return the Roman numeral representation of the integer
* @throws IllegalArgumentException if the integer is negative or greater than the maximum Roman numeral value
*/
public static String toRoman(int value)
throws IllegalArgumentException
{
try {
return ROMAN_NUMERALS_BY_VALUE[value];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Roman numerals can only represent non-negative values up to " + MAX_ROMAN + ", but not: " + value);
}
}
/** Helper enum for creating Roman numerals in a simple way. Only used during class initialization. */
private enum Symbol
{
M(1000),
CM(900),
D(500),
CD(400),
C(100),
XC(90),
L(50),
XL(40),
X(10),
IX(9),
V(5),
IV(4),
I(1);
private static final Symbol[] SYMBOLS = values();
public final int value;
Symbol(int value)
{
this.value = value;
}
private int appendIfPossible(int input, StringBuilder collect)
{
while (input >= value) {
input -= value;
collect.append(name());
}
return input;
}
private static String toRoman(int number, StringBuilder reused)
{
assert number >= 0 && number <= MAX_ROMAN;
reused.setLength(0);
for (Symbol symbol : SYMBOLS) {
number = symbol.appendIfPossible(number, reused);
}
return reused.toString();
}
}
}
This is standalone, quite short, perfectly simple and really fast. It just caches all possible 4000 Roman numbers two ways:
- in an array, for access by value.
- in a
Map, for access by text representation.
The private enum RomanNumerals.Symbol provides a simple way to create a Roman numeral from its value.
It’s not used after the class is fully initialized.
Note that this implementation uses the empty string "" for 0.
Change this if that is not appropriate in your use case.
To make its usage easier I didn’t make use of my special classes like Indexable, just pure standard Java (8 at least).
Appendix
Downloads
The sources of the above programs: roman-numerals.zip.
Contents of the ZIP:
| Path | Description | Needs de.caff? |
|---|---|---|
src/playground/roman/ |
Package directory. | n.a. |
src/playground/roman/FromRomanAxolot.java |
Axolot’s improved version of Bob’s code, ported to Java 8. | no |
src/playground/roman/FromRomanUncleBob.java |
Bob’s first delibrately bad version, repaired for MCM, ported to Java 8. | no |
src/playground/roman/FromRomanUncleBob2.java |
Bob’s improved version, ported to Java 8. | no |
src/playground/roman/InvalidRomanNumeralException.java |
Resued exception to make the other examples smaller. And this is a NumberFormatException and not a RuntimeException as in the original code. |
yes |
src/playground/roman/RomanNumerals.java: |
This is the code of the standalone fast pure-standard-java class. | no |
src/playground/roman/RomanNumeralsGrok.java |
Grok’s idea of rewriting Bob’s code. | no |
src/playground/roman/RomanNumeralsGrokFurtherImproved.java |
A slightly more optimized version the improved Grok version (see next row). | no |
src/playground/roman/RomanNumeralsGrokImproved.java |
Grok’s code, with some evident adhoc improvements, as described in this post. | no |
src/playground/roman/RomanNumeralsGrokNoCheck.java |
DON’T USE! Broken Grok code without testing for invalid numberals. Shows how much time regexp pattern matching is eating up. | no |
src/playground/roman/RomanNumeralsRammi.java |
My idea of how to parse Roman numerals. | yes |
src/playground/roman/RomanNumeralsRammiFast.java |
Basically the same as RomanNumerals, but using my lib. |
yes |
src/playground/roman/SpeedTest.java |
Comparison of the above classes. | yes |
src/playground/roman/package-info.java |
As usual. | no |
In order to be able to compile everything and run the tests you’ll also need the following lib used in some classes:
- caff-generics.jar, see de·caff Commons for background.
Speed Test Result
The speed test parses all 4,000 Roman numerals a 1,000 times in a single thread on an AMD Ryzen 9 5950X 16-Core Processor.
| Tested Class | Duration | "IXI" is an error? |
Comments |
|---|---|---|---|
| FromRomanUncleBob | 3768 ms | yes | |
| FromRomanUncleBob2 | 922 ms | yes | Probably improvements from removed usages of String.replace() |
| FromRomanAxolot | 1004 ms | yes | |
| RomanNumeralsGrok | 2741 ms | yes | |
| RomanNumeralsGrokImproved | 638 ms | yes | Avoids String.matches() |
| RomanNumeralsGrokFurtherImproved | 606 ms | yes | 2-minutes improvement of the above using NI |
| RomanNumeralsGrokNoCheck | 33 ms | NO, and this is bad! | Included to show slowness of regexp matching which used some 95% of the runtime. |
| RomanNumeralsRammi | 297 ms | yes | A lot of code constructed from understanding the problem. |
| RomanNumeralsRammiFast | 29 ms | yes | Fast, but using non-standard immutable collection classes like Indexable (a read-only List), and RomanNumeralsRammi to create Roman numerals. |
| RomanNumerals | 45 ms | yes | Pure Java standalone version of the above, should run nearly as fast. But immutable code is easier to improve by the JIT. Or the JIT has just seen more Indexables in the test. |