Skip to content

Latest commit

 

History

History
585 lines (501 loc) · 34.4 KB

IMPLEMENTATION.md

File metadata and controls

585 lines (501 loc) · 34.4 KB

Transition Tables

RFC 4180 grammar defines a regular language.1 By definition, a regular language is the set of strings recognised by a finite state automaton (FSA).

Under the hood, many CSV parsers are finite state automata. For example, when a parser encounters a double quote character, it could transition to the INSIDE_QUALIFIED_FIELD state; a second double quote could make the parser transition to the END_QUALIFIED_FIELD state. These would be two of the finite number of states in the parser.

There are many ways to implement a finite state automaton, one of which is to keep the current state in a variable. In SimpleFlatMapper, the author arnaudroger uses precisely this technique.

while (currentIndex < bufferSize) {
    final char character = chars[currentIndex];
    if (character == separatorChar) {
        // ...
        currentState = LAST_CHAR_WAS_SEPARATOR | ROW_DATA;
        continue;
    } else if (character == LF) {
        // ...
        currentState = NONE;
        continue;
    } else if (character == CR) {
        // ...
        currentState = LAST_CHAR_WAS_CR;
        continue;
    } // ...
}

In the example above2, the state of the parser changes by updating currentState and the change is driven by the flow of the code: a cascade of if-else statements decides which state is next. This technique is simple and very effective and, in fact, SimpleFlatMapper is one of the fastest Java CSV parsers in circulation.

skjolberg takes a slightly different approach. In sesseltjonna-csv the state is kept implicit. There is no currentState variable; instead, the execution point implicitly defines the state of the automaton3.

if (current[currentOffset] != quoteCharacter) {
    // Implicit state: AT_START_OF_FIELD
    // ...
    if (current[currentOffset] != divider) {
        // Implicit state: IN_UNQUALIFIED_FIELD
        // ...
    } else {
        // Implicit state: IN_EMPTY_FIELD
        // ...
    }
} else {
    // Implicit state: IN_QUALIFIED_FIELD
    // ...
}

Performance-wise, the implicit state technique works really well, and currently sesseltjonna-csv is the fastest single-threaded Java CSV parser I know. In both SimpleFlatMapper and sesseltjonna-csv, transitions from one state to the next are not explicit, and their logic is pushed deep within the code. With these two models, understanding state transitions is difficult.

mneri/csv takes a different approach: all the states are explicitly laid out in a transition table. Rows represent states, columns represent input characters, and the intersections indicate the next state.

|                 | [A-Za-z0-9]     | ,               | \r              | \n              | "               | EOF         |
+-----------------+-----------------+-----------------+-----------------+-----------------+-----------------+-------------+
| BEFORE_LINE *   | FIELD           | BEFORE_FIELD    | CAR             | ERROR           | START_QUALIFIED | END_OF_FILE |
| BEFORE_FIELD    | FIELD           | BEFORE_FIELD    | CAR             | ERROR           | START_QUALIFIED | END_OF_FILE |
| FIELD           | FIELD           | BEFORE_FIELD    | CAR             | ERROR           | ERROR           | END_OF_FILE |
| START_QUALIFIED | QUALIFIED_FIELD | QUALIFIED_FIELD | QUALIFIED_FIELD | QUALIFIED_FIELD | ESCAPE          | ERROR       |
| QUALIFIED_FIELD | QUALIFIED_FIELD | QUALIFIED_FIELD | QUALIFIED_FIELD | QUALIFIED_FIELD | ESCAPE          | ERROR       |
| ESCAPE          | ERROR           | BEFORE_FIELD    | CAR             | ERROR           | QUALIFIED       | END_OF_FILE |
| CAR             | ERROR           | ERROR           | ERROR           | BEFORE_LINE     | ERROR           | ERROR       |
| END_OF_FILE     | ERROR           | ERROR           | ERROR           | ERROR           | ERROR           | ERROR       |
| ERROR           | ERROR           | ERROR           | ERROR           | ERROR           | ERROR           | ERROR       |

The transition table above can be used to parse a CSV file that is fully compliant with RFC 4180.4 The initial state is BEFORE_LINE (marked with *). Upon consuming the character a (first column), the state transitions to FIELD. From the FIELD state, a comma sets the transition to BEFORE_FIELD (the "cursor" is positioned before the next field). Transitions continue until either the state END_OF_FILE or ERROR are reached. To be fully compliant with RFC 4180, the transition table must reject malformed inputs. In the example above, ERROR is a sink state; once entered, it cannot be left because all outgoing transitions loop back to itself.

A transition table makes it easier to reason about the parser and document its behaviour. All the states and transitions are laid out clearly in a single point.

When transitioning from one state to the next, the parser shall perform some actions. Actions can be encoded in the transition table along with the state changes. Below is an example for the BEFORE_LINE state shown above.

|               | [A-Za-z0-9]         | ,                             | \r               | \n                      | EOF                 |
+---------------+---------------------+-------------------------------+------------------+-------------------------+---------------------+
| BEFORE_LINE * | next:   FIELD       | next:   BEFORE_FIELD          | next:   CAR      | next:   ERROR           | next:   END_OF_FILE |
|               | action: START_FIELD | action: START_FIELD,END_FIELD | action: END_LINE | action: THROW_EXCEPTION | action: STOP        |

Consuming the character a while in state BEFORE_LINE makes the parser transition to the state FIELD and record the start of a field (START_FIELD action).

Querying a transition table for every character carries a very noticeable performance penalty. Approaches like SimpleFlatMapper and sesseltjonna-csv are inherently faster because they don't pay for these array lookups. In mneri/csv, however, an explicit transition table is a non-negotiable core requirement. Much of the rest of this document focuses on performance, in an attempt to overcome this architectural penalty.

Formats

mneri/csv supports many different CSV dialects, each one implemented as a separate transition table and enclosed in a Format implementation.

Transition tables are implemented using int[] and as explained before, states and actions are encoded together: the low 16 bits of each element encode the target state, while the high 16 bits encode the corresponding actions. Below is the transition table for Rfc4180StrictFormat. While it looks complex, it is actually quite straightforward.

private static final int[] DFA = {
// *            ,            \r           \n           "            EOF                  padding
   FLD,         BFF|EFH,     CAR|EFH,     ERR|ERH,     ERR|ERH,     EOF|EFH|ELH|RPL,     0,0,  // FLD
   QOT,         QOT,         QOT,         QOT,         ESC,         ERR|ERH,             0,0,  // QOT
   FLD|SFH,     BFF|SFH|EFH, CAR|SFH|EFH, ERR|ERH,     SQT,         EOF|SFH|EFH|ELH|RPL, 0,0,  // BFF
   QOT|SFH,     QOT|SFH,     QOT|SFH,     QOT|SFH,     SQE,         ERR|ERH,             0,0,  // SQT
   ERR|ERH,     BFF|EFB,     CAR|EFB,     ERR|ERH,     QOT|RMB,     EOF|EFB|ELH|RPL,     0,0,  // ESC
   ERR|ERH,     BFF|SFH|EFH, CAR|SFH|EFH, ERR|ERH,     QOT|SFH,     EOF|SFH|EFH|ELH|RPL, 0,0,  // SQE
   FLD|SFH,     BFF|SFH|EFH, CAR|SFH|EFH, ERR|ERH,     SQT,         EOF|STP,             0,0,  // BFL *
   ERR|ERH,     ERR|ERH,     ERR|ERH,     BFL|ELH,     ERR|ERH,     ERR|ERH,             0,0,  // CAR
   ERR|ERH,     ERR|ERH,     ERR|ERH,     ERR|ERH,     ERR|ERH,     EOF|STP,             0,0,  // EOF
   ERR|ERH,     ERR|ERH,     ERR|ERH,     ERR|ERH,     ERR|ERH,     ERR|ERH,             0,0,  // ERR
// padding      padding      padding      padding      padding      padding              padding
   0,           0,           0,           0,           0,           0,                   0,0,
   0,           0,           0,           0,           0,           0,                   0,0,
   0,           0,           0,           0,           0,           0,                   0,0,
   0,           0,           0,           0,           0,           0,                   0,0,
   0,           0,           0,           0,           0,           0,                   0,0,
   0,           0,           0,           0,           0,           0,                   0,0};

Rows represent the current state, and columns represent classes of characters. On the right-hand side of each row there is a comment indicating the state name, and the starting state is noted with an *. A line comment above the table labels the columns. The first column is labelled with *, meaning any character other than those listed in the subsequent columns. Next, in order, come the columns for ,, \r, \n, ", and EOF (end of file). The padding around rows and columns is a low-level optimization, and is explained later on in the document. Cells encode both the next state and the actions. For example, the cell BFF|EFH encodes both the "before field" state and the "end field at the current position" action. The first element in each cell is always the state.
States and actions appear in the code as three-letter mnemonics, shown in alphabetical order in the tables below.

| STATE MNEMONIC  | MEANING                                | STATE MNEMONIC  | MEANING                                |
|-----------------|----------------------------------------|-----------------|----------------------------------------|
| BFF             | before field                           | ESC             | escape in qualified field              |
| BFL             | before line                            | FLD             | field                                  |
| CAR             | carriage return                        | QOT             | qualified field                        |
| EOF             | end of file                            | SQE             | escape at the start of qualified field |
| ERR             | error                                  | SQT             | start of qualified field               |


| ACTION MNEMONIC | MEANING                                | ACTION MNEMONIC | MEANING                                |
|-----------------|----------------------------------------|-----------------|----------------------------------------|
| EFB             | end field at the previous position     | RMB             | remove the previous character          |
| EFH             | end field at the current position      | RPL             | replay the last character              |
| ELB             | end line at the previous position      | SFH             | start field at the current position    |
| ELH             | end line at the current position       | STP             | stop processing                        |
| ERH             | report error at the current position   |                 |                                        |

The transition table is hidden behind the Format's consume() method.

state = format.consume(state, nextChar);

Given the current state and the next input character, consume() returns the next state and actions, consulting its private transition table.

As mentioned before, mneri/csv implements different CSV formats; most notably:

  • Rfc4180StrictFormat: strict interpretation of the RFC 4180 specification, throwing an exception if the document is not compliant.
  • Rfc4180HalfRelaxedFormat: a more relaxed interpretation of RFC 4180, allowing for different line termination characters, and misplaced double-quotes.
  • Rfc4180FullyRelaxedFormat: a fully relaxed interpretation of RFC 4180 that is guaranteed to never throw an exception because of format errors.5
  • MsExcelFormat: a format implementation inspired by Microsoft Excel's behaviour.
  • MacintoshFormat: an interpretation of RFC 4180 compliant with legacy Macintosh systems where the line separator is \r.

Parsers

In this architecture, parsers are responsible for reading characters from the input stream, feeding them to the format, and executing any actions dictated by the format.

public void parse() {
    do {
        state = format.consume(state, nextChar());
        if (isStartOfField(state)) {
            // ...
        }
        if (isEndOfField(state)) {
            // ...    
        }
        // ...
    } while // ...
}

private boolean isStartOfField(int state) {
    return (state & SFH) != 0; 
}

Action flags are checked using a simple bitwise & operation (state & SFH). If the flag is set, the parser shall take the corresponding action.

There is a clear separation of mechanism (the parser) and policy (the format). This separation allows different CSV dialects to be plugged seamlessly into the high-performance parsing pipeline without duplicating stream-handling or optimization logic.

The parser components are deliberately kept stupid (and that's a compliment). The parser's main loop is incredibly simple and just about 20 lines of code.

Vector API

The Vector API is an exciting feature of JDK 16 and above that allows engineers to access CPU vector operations.

Vector operations (also known as SIMD, Single Instruction Multiple Data) can substantially speed up computation. Instead of processing values one-by-one in a sequential loop, the CPU computes an entire blocks of data in a single clock cycle. For some time now, the Java C2 JIT compiler can transform tight loops into vector operations, but the result has always been somewhat unreliable. The Vector API gives engineers explicit control. If the Java runtime supports the Vector API (JDK 17 and above, with --add-modules jdk.incubator.vector), mneri/csv will leverage vector operations. If not, it will fall back to sequential operations.

mneri/csv uses vector operations to calculate a 64-bit mask. The mask indicates which characters must be processed, and which can be ignored. In the example below, bits are set at key positions (such as the first character of a field, commas, and new-line characters).

CSV chunk: a a a a , b b b b , c c c c \r\n
Mask:      1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1

Processing only these characters is sufficient to keep the state machine consistent, while the characters with bits set to zero can be safely skipped. The mask can occasionally contain false-positives, for example a comma enclosed in a qualified field (this is unavoidable, but luckily rare). In this case, the state machine knows it is inside a qualified field and correctly ignores the comma.

Below is an abstraction of the vectorised parser's loop6.

do {
    while (bitmask == 0L) {
        strideStart += STRIDE; // The stride is 64 characters for a 64-bit bitmask
        bitmask = format.bitmask(state, buf, strideStart);
    }
    shift = Long.numberOfTrailingZeros(bitmask);
    bitmask &= bitmask - 1L; // Kernighan's trick
    pos = strideStart + shift;

    state = format.consume(state, buf[pos]);
    if (isStartOfField(state)) {
        // ...
    }
    if (isEndOfField(state)) {
        // ...
    }
} while // ...

The parser maintains a 64-character window (stride). The bitmask tells which characters to process, and which not. Using Kernighan's trick the bitmask is zeroed one bit at a time. Please, note that Long.numberOfTrailingZeros() is a HotSpot intrinsic which in modern CPUs is compiled into a tzcnt instruction with a latency of ~1 CPU cycle. Much like the sequential parser, the vector parser logic is incredibly simple and its main loop is about 30 lines of code.

Calculating the mask is not free, but the cost is very well offset by the savings downstream.

Benchmark Size (Characters) Transition Table Lookups Reduction
maxmind/worldcitiespop.txt 129,212,350 35,140,321 72.80%
gtfs/trips.txt 12,274,080 1,715,898 86.02%
gtfs/stop_times.txt 253,105,642 53,130,902 79.01%

The table above shows the lookup reduction in three popular benchmarks. This result is not absolute and heavily depends on the input file.

In Parsing CSV with SIMD, Matthew Kim presents an algorithm that (at least on the surface) promises higher throughput than the vector approach used here. For example, his technique entirely eliminates false-positives and doesn't require to process the character at the start of a field. In mneri/csv, however, the transition table is a non-negotiable core of the architecture. Maintaining an explicit, easy-to-reason-about transition table comes with trade-offs like accepting a less optimal masking strategy.

Paging

The CsvReader exposes a simple API. Note how lines are returned one by one when the client calls next().

try (CsvReader<Contact> reader = CsvReader.open(new File("contacts.csv"), StandardCharsets.UTF_8, new ContactDeserializer())) {
    while (reader.hasNext()) {
        Contact contact = reader.next();
        // ...
    }
}

Internally, the mechanics are quite different. Lines are parsed in blocks called pages (by default, 4096 characters). All the lines in a page are parsed at once. The parser hands the page to the CsvReader which operates a cursor and returns one line at a time (exposing a nice and simple interface to the client).

Working with pages has important performance benefits.

  • The CPU registers stay hot for longer. Inside the parser loop, hot variables (such as the active state, buffers, indexes and offsets) stay pinned in the hardware registers throughout the entire block.
  • Data stays in the CPU caches. A page is small on purpose: 4096 characters (8 KB in standard Java UTF-16 representation) can comfortably fit inside the L1 or L2 data cache of modern CPUs, so there's a better chance the parser operates entirely at cache speed.
  • Helps the hardware prefetcher. Accessing memory sequentially gives the CPU spatial prefetcher a deterministic access pattern, allowing it to load upcoming cache lines before the parser requests them.

Performances increased by 10-15% when paging was introduced.

Pages are recycled, and there is a small and fixed number of them at all times. Once the client has consumed all the lines, the page is cleared and handed back to the parser. Lines rarely align with page boundaries; when a line is split across pages, the trailing characters are copied to the beginning of the next page before parsing.

Each page uses a single line instance, called RecycledLine: a flyweight facade that slides across the page buffer. Rather than allocating new objects for every record, RecycledLine updates its internal offset pointers as the cursor moves.

Multithreading

The table below shows profiling results for single-threaded parsing, broken down by phase.

Dataset Phase Class Execution Time Execution %
WORLD_CITIES_POP I/O (Reading and decoding) java.io.Reader 26.2 ms 6.7%
Parsing VectorPageParser 159.6 ms 40.5%
Deserializing (domain object creation) StringArrayDeserializer 207.9 ms 52.8%
Total 393.7 ms 100%

Note: It is not possible to measure these parts in isolation with JMH; the values are obtained by measuring cumulative stages (read; read and parse; read, parse and deserialize) and subtracting. The phases compete for the same caches and branch predictors, so the split is approximate.

Note: I/O time is low because files are kept in the OS page cache during benchmark runs.

A parallel CsvReader splits the work between two threads:

  • A background thread reads the stream and parses it into pages.
  • The client's thread deserializes the lines into domain objects (in the table above, each CSV line is mapped to a String[]).

While the client thread deserializes the lines of a page, the background thread concurrently parses the next page.

Notice how reading and parsing together account for 47.2% of execution time, while deserialization accounts for 52.8%. Because the workload is split almost evenly, this two-stage pipeline cuts the execution time significantly.

Concurrency is managed using two ArrayBlockingQueue instances named free and loaded. The background thread takes a page from free (blocking if empty), populates it with parsed data, and places it into loaded. The client thread retrieves pages from loaded (blocking if empty), deserializes the lines, and returns the consumed page back to free. The synchronization overhead is therefore amortized across hundred of records per page rather than paid on every line.

Multithreading is strictly opt-in. To instantiate a parallel CsvReader, callers invoke one of the CsvReader.parallel() factory methods and supply a ThreadFactory. Some Java parsers (such as univocity-parsers) enable parallel execution by default and require explicit opt-out configuration. In my opinion, this is not correct and mneri/csv takes the opposite stance.

Low-Level Optimisations

Maintaining the state in a local variable or relying on the execution stack to keep an implicit state (like SimpleFlatMapper and sesseltjonna-csv do respectively) is generally faster than querying a transition table for every character in the stream. mneri/csv mitigates this architectural penalty with a series of low-level optimisations.

Branchless Column Mapping

As explained earlier, the parser decides its next state by querying a transition table. To do the lookup, it first needs to translate the current character into a column index.

Rfc4180StrictFormat performs a mapping equivalent to the following:

if (c == ',') {
    return 1;
} else if (c == '\r') {
    return 2;
} else if (c == '\n') {
    return 3;
} else if (c == '"') {
    return 4;
} else if (c == -1) {
    return 5;
} else {
    return 0;
}

However, branching introduces a major performance bottleneck due to possible misprediction. Modern CPUs rely on branch predictors to guess execution paths and pre-fill the pipeline. In a CSV stream, this mechanism breaks down. Real-world data alternates unpredictably between long stretches of ordinary text and sparse structural markers like commas, quotes, and newlines. Because these tokens appear at irregular intervals depending on the data content, branch predictors cannot establish a reliable pattern. Every misprediction triggers a costly pipeline flush, stalling the CPU. Luckily, we can remove most of these branches by changing our approach.

Column mapping happens in two distinct steps. The first step uses a bitmask to quickly filter out ordinary text characters.

We construct a 64-bit mask where individual bit positions correspond to the ASCII values of our control characters. For example, line feed (\n) has an ASCII code of 10, so the 10th bit of the mask is set to 1. Carriage return (\r) has an ASCII code of 13, setting the 13th bit. The same goes for the characters , and ".

if (c > ',' || ((1L << c) & 0x80_00_10_04_00_00_24_00L) == 0) {
    return 0;
}

Java's shift operators automatically mask shift amounts to 63 (c & 63). That means any character code of 64 or higher will wrap around and risk hitting one of our precious bit flags. Since the comma (44) is our highest-value control character, anything strictly greater than it is guaranteed to be ordinary text. The c > ',' check acts as a bypass: it immediately accepts any character above the comma's ASCII value (since nothing higher is a control token) while preventing high-value inputs from wrapping around and colliding with our bitmask.

Once a character passes our filter, we know for a fact that it is one of our control tokens. Now, instead of a slow switch statement, we use a compressed lookup table packed inside a single 64-bit constant. This is step two.

return (int) (0x00_00_20_20_00_00_98_05L >>> (c + 1)) & 0x7;

Building this lookup table follows the same logic as our mask, but instead of setting a single 1 bit to flag a control character, we store a 3-bit integer representing its column index in the transition table. For example, in Rfc4180StrictFormat, the character \r (ASCII 13) is mapped to column 2 of the transition table and 2 in binary is 010; so, we place 010 in the map at position 13 in the bit map. \n (ASCII 10) is mapped to column 3 of the transition table and 3 in binary is 011; so, we place 011 at position 10 in the bit map.

By replacing a switch or if-else chain with a bit-packed map, we trade unpredictable control flow for pure register math. A conditional chain forces the CPU to guess execution paths, risking costly pipeline stalls every time a branch mispredicts.

Super-Hot Path Shortcut

Table lookups can be cheap, but a single register comparison is certainly cheaper. Profiling showed that the single most common transition is from state FLD (FIELD) and receiving an ordinary character. This case accounts for the majority of transitions of a typical CSV file, so it's been hardcoded.

public int consume(int s, int c) {
    if (s == FLD && c > ',') {
        return FLD;
    }
    // Otherwise, perform a table lookup.
}

Everything else falls through a transition table lookup.

Optimization of the Lookup

mneri/csv makes heavy use of transition tables, and their optimization is very important.

The JIT compiler can optimize array access, if the conditions are right. Transition tables are padded to 128 elements, which is a power of two, and the access is masked as show below.

return DFA[index & 0x7F];

0x7F constrains the index to [0, 127]. Thanks to the mask, the JIT compiler is able to prove that the index is always between the bounds and eliminates the array bounds check, as shown in the assembly below.

and    $0x7f,%r10d
movabs $0x71327cd48,%r11    ; {oop([I{0x000000071327cd48})}
mov    0x10(%r11,%r10,4),%eax

We can also observe that the JIT compiler folded the address of the transition table: the array reference is treated as a constant directly embedded in the assembly, and reused without reloading it from an object field; in the example above, movabs loads the hardcoded constants into the r11 CPU register, then mov loads the array element into the eax register.

The lookup happens inside the Format's consume() method. We can observe that the method was fully inlined into the ScalarPageParser and VectorPageParser code.

It is to be said that the behaviour of the JIT compiler, and especially inlining, can vary between executions and is not a guarantee, but this is as good as it can get.

Other Low-Level Optimisations

Facilitating Method Inlining

Every time a method is invoked, the CPU must incur the cost of setting up a stack frame, jumping to a new memory address, and returning once finished. For small, frequently executed methods (like getters), the overhead can easily eclipse the actual execution time. The JIT compiler is capable of inlining short methods (removing the cost of the call completely), and it is more likely to do so when its bytecode is small.

mneri/csv structures hot methods to keep the common case short and inlineable, pushing uncommon code paths and error handling into a separate, cold method that is only reached when needed. An example of this can be found in CsvReader. Clients are expected to use this class following the idiomatic hasNext()-next() pattern, as shown below.

try (CsvReader<Contact> reader = CsvReader.open(new File("contacts.csv"), StandardCharsets.UTF_8, new ContactDeserializer())) {
    while (reader.hasNext()) {
        Contact contact = reader.next();
        // ...
    }
}

Lines are parsed a page at a time, so the next line is almost always in the current page: in the common case, hasNext() only has to compare the cursor with the number of lines in the page.

public boolean hasNext() throws IOException {
    return cursor < page.lineCount() || hasNext2(); // hasNext2() is only called at the end of the page
}

Notice how hasNext() performs a single comparison, skipping other sanity checks like verifying whether the reader is still open. This minimalism keeps the bytecode footprint tiny and the method is very likely to be inlined in the caller. All the edge-cases are handled by the hasNext2() method.

private boolean hasNext2() throws IOException {
    if (closed) {
        throw new IllegalStateException("The reader is closed.");
    }
    while (cursor == page.lineCount()) {
        if (page.error() != null) {
            throw rethrow(page.error());
        }
        if (page.isLast()) {
            return false;
        }
        flip(); // Load the next page
        cursor = 0;
    }
    return true;
}

hasNext2() is called once per page, not once per line. It catches a closed reader too: close() moves the cursor past the end of the page, so hasNext() doesn't need to check. next() reuses hasNext().

public T next() throws IOException {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    return deserializer.deserialize(page.line(cursor++));
}

This technique is not limited to the CsvReader class, but used throughout the code. Another example can be found in InternalRecycledLine, which implements RecycledLine.

public String getString(int n) throws IOException {
    if (n < 0 || n >= getFieldCount()) {
        noSuchFieldException(n);
    }
    int i = from + 2 * n;
    int length = fieldLength(i);
    if (length == 0) {
        return null;
    }
    if (!isDirty()) {
        return new String(buf, fieldStart(i), length);
    }
    return getDirtyString(n, length);
}

A line is dirty when the parser removed characters from it, such as the first double quote of an escaped "". Most lines are clean, and their fields are copied straight from the page buffer; getDirtyString() skips the removed characters of the others. We need getString() to be inlined, and to push the JIT compiler to do so we must keep it as lean as possible. We are happy to pay a full method call for getDirtyString() because it happens so infrequently.

It sounds off, but sometimes you can get better performances by adding a method call.

Performances

See PERFORMANCE.md for the full results, performance analysis, hardware details, and commands for running the benchmarks.

Below, the comparison of mneri/csv performances against other Java frameworks using the popular worldcitiespop.csv benchmark. mneri/csv in Parallel/Vector configuration currently score the fastest.

Dataset Rank Benchmark Score (ms/op) Error
WORLD_CITIES_POP 🥇 1 mneri/csv (Parallel/Vector) 269.871 ± 4.864
🥈 2 sesseltjonna-csv 301.261 ± 2.603
🥉 3 mneri/csv (Parallel/Scalar) 355.175 ± 42.196
4 mneri/csv (Sequential/Vector) 386.606 ± 1.966
5 SimpleFlatMapper 490.333 ± 4.741
6 univocity-parsers (Parallel Reader) 496.941 ± 5.912
7 FastCSV 504.354 ± 4.661
8 univocity-parsers (Standard Reader) 521.132 ± 7.527
9 mneri/csv (Sequential/Scalar) 532.251 ± 26.342
10 Quick CSV Streamer 534.030 ± 5.720
11 picocsv 551.995 ± 5.128
12 Jackson CSV 774.857 ± 3.951
13 JavaCSV 1,066.995 ± 22.780
14 Super CSV 1,176.623 ± 13.487
15 opencsv 1,181.589 ± 6.937
16 Apache Commons CSV 2,720.958 ± 10.256

Footnotes

  1. As defined by the ABNF grammar in RFC 4180 it is a regular language. The document also lists a series of rules, one of which saying "Each line should contain the same number of fields throughout the file". This rule would make it not a regular language. ↩

  2. See SimpleFlatMapper's ConfigurableCharConsumer.java ↩

  3. See sesseltjonna-csv's DefaultStringArrayCsvReader.java ↩

  4. The statement is imprecise: Rfc4180StrictFormat allows lines to contain different number of fields. In section 2 ("Definition of the CSV Format"), RFC 4180 states "Within the header and each record, there may be one or more fields, separated by commas. Each line should contain the same number of fields throughout the file" (please note, the use of "should" and not "must"). The client can easily enforce this rule in their custom Deserializer. ↩

  5. Rfc4180FullyRelaxedFormat ignores all format errors, but some exceptions (such as IOException) can still happen. ↩

  6. For the full implementation, see VectorPageParser.java ↩