Skip to content
Open
105 changes: 105 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,83 @@ record SimdJsonTwitter(List<SimdJsonStatus> statuses) {
}
```

### On-Demand Parser

The on-demand parser builds no DOM. `parseOnDemand` indexes the document and returns a forward-only cursor that decodes
only the values you ask for and skips everything else with `skipChild()`. Strings and field names are decoded into your
own byte array, which needs `OnDemandJsonIterator.STRING_BUFFER_PADDING` spare bytes after the longest string you expect.

```java
byte[] json = loadTwitterJson();
byte[] statuses = "statuses".getBytes(UTF_8);
byte[] id = "id".getBytes(UTF_8);
byte[] name = new byte[64 + OnDemandJsonIterator.STRING_BUFFER_PADDING];

SimdJsonParser parser = new SimdJsonParser();
OnDemandJsonIterator it = parser.parseOnDemand(json, json.length);
if (it.startIteratingRootObject() == IteratorResult.NOT_EMPTY) {
do {
int nameLength = it.getFieldName(name);
it.moveToFieldValue();
if (!Arrays.equals(name, 0, nameLength, statuses, 0, statuses.length)) {
it.skipChild();
} else if (it.startIteratingArray() == IteratorResult.NOT_EMPTY) {
do {
if (it.startIteratingObject() == IteratorResult.NOT_EMPTY) {
do {
nameLength = it.getFieldName(name);
it.moveToFieldValue();
if (Arrays.equals(name, 0, nameLength, id, 0, id.length)) {
System.out.println(it.getNonNullLong());
} else {
it.skipChild();
}
} while (it.nextObjectField());
}
} while (it.nextArrayElement());
}
} while (it.nextObjectField());
}
```

`peekType()` tells you the JSON type of the next value before you pick a getter. The cursor belongs to its parser and is
valid until the parser's next parse call. See the javadoc of `OnDemandJsonIterator` for the details, including how to skip
the rest of an object or array from inside it.

### Allocation-Free Navigation

`JsonValue` can also be navigated with plain `int` indices, which avoids allocating a `JsonValue`, an iterator or a
`String` per value. Field names are passed as pre-encoded byte arrays, and strings can be read straight from the parser's
buffer with `stringBytes()`, `byteOffset(int)` and `byteLength(int)`.

```java
JsonValue doc = parser.parse(json, json.length);
int tweets = doc.field(doc.index(), STATUSES);
if (tweets >= 0 && doc.isArrayAt(tweets)) {
int end = doc.scopeEnd(tweets);
for (int tweet = doc.firstElement(tweets); tweet >= 0 && tweet < end; tweet = doc.advance(tweet)) {
int id = doc.isObjectAt(tweet) ? doc.field(tweet, ID) : -1;
if (id >= 0 && doc.isLongAt(id)) {
System.out.println(doc.longAt(id));
}
}
}
```

Methods that need a value of a particular type, such as `field` or `longAt`, throw an `IllegalArgumentException` for an
index of another type; the `is...At` methods test the type first.

### Skipping UTF-8 Validation

By default, every document is validated as UTF-8. If your input is already known to be valid, for example because a
trusted component produced or checked it, you can skip that step:

```java
SimdJsonParser parser = new SimdJsonParser(capacity, maxDepth, false);
```

Invalid UTF-8 is then not detected, and strings decoded from it may be malformed.

## Installation

The library is available in the [Maven Central Repository](https://mvnrepository.com/artifact/org.simdjson/simdjson-java).
Expand Down Expand Up @@ -81,6 +158,34 @@ To run the JMH benchmarks, execute the following command:

```./gradlew jmh```

### Synthea FHIR Benchmark

[SyntheaBundleBenchmark](src/jmh/java/org/simdjson/synthea/SyntheaBundleBenchmark.java) extracts a fixed set of fields
from [Synthea](https://github.com/synthetichealth/synthea) FHIR bundles with the DOM, index-based, on-demand and
schema-based APIs. No data is included: generate bundles with Synthea and point the benchmark at the output directory.
Build the benchmark jar first:

```./gradlew clean jmhJar```

Check that all modes extract the same values (exit status 0 when they agree):

```
java --add-modules jdk.incubator.vector -Dsynthea.dir=/path/to/output/fhir \
-cp build/libs/simdjson-java-*-jmh.jar org.simdjson.synthea.SyntheaBundleVerifier
```

Run the benchmark:

```
java -jar build/libs/simdjson-java-*-jmh.jar 'org.simdjson.synthea.SyntheaBundleBenchmark' \
-jvmArgsPrepend '--add-modules=jdk.incubator.vector' \
-jvmArgsAppend '-Xmx8g -Dsynthea.dir=/path/to/output/fhir'
```

Both take the same system properties: `synthea.dir` (required), `synthea.maxFiles` (default 256), `synthea.maxBytes`,
`synthea.expectFingerprint` and `synthea.validateUtf8` (default `true`). Files are selected in a fixed order, and the
printed fingerprint identifies the selection.

## Tests

To run the tests, execute the following command:
Expand Down
6 changes: 6 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ test {
// We use mustRunAfter so they don't interleave output if run together via 'check'.
dependsOn tasks.named('test')

// Gradle 9 no longer wires custom Test tasks to the test source set.
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath

useJUnitPlatform()
jvmArgs += [
'--add-modules', 'jdk.incubator.vector',
Expand All @@ -180,6 +184,8 @@ tasks.withType(JavaCompile).configureEach {
}

tasks.compileJmhScala.classpath = sourceSets.main.compileClasspath
// Scala 2.13.16 cannot emit class files for Java 25+, so the Scala benchmark sources target Java 21.
tasks.compileJmhScala.scalaCompileOptions.additionalParameters = ['-release:21']
tasks.compileJmhJava.classpath += files(sourceSets.jmh.scala.classesDirectory)

compileTestJava {
Expand Down
133 changes: 133 additions & 0 deletions src/jmh/java/org/simdjson/synthea/SyntheaBundleBenchmark.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package org.simdjson.synthea;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.simdjson.SimdJsonParser;

import java.util.concurrent.TimeUnit;

/**
* Extracts a fixed set of fields from Synthea FHIR bundles (see {@link SyntheaExtractor}) with each
* parsing mode.
* <p>
* One benchmark operation is one pass over the whole corpus, so the score (average time per operation)
* converts to throughput as {@code totalBytes / score} and {@code files / score}; both numbers are
* printed by the trial setup. With {@code -t N}, each of the N threads makes its own full pass per
* operation, with its own parser, over the shared read-only corpus.
* <p>
* The corpus is selected by system properties of the forked JVM; see {@link SyntheaCorpus}. The property
* {@code synthea.validateUtf8} (default {@code true}) selects whether the parsers validate UTF-8; the trial setup
* prints the setting. Before any
* measurement, the trial setup checks that all modes agree on the first few files and refuses to run
* if they do not.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class SyntheaBundleBenchmark {

private static final int AGREEMENT_CHECK_FILES = 4;

@State(Scope.Benchmark)
public static class CorpusState {

SyntheaCorpus corpus;
boolean validateUtf8;

@Setup(Level.Trial)
public void setup() {
corpus = SyntheaCorpus.fromSystemProperties();
corpus.printSummary(System.out);
validateUtf8 = SyntheaExtractor.validateUtf8FromSystemProperties();
System.out.println(SyntheaExtractor.VALIDATE_UTF8_PROPERTY + "=" + validateUtf8);
SyntheaBundleVerifier.Report report =
SyntheaBundleVerifier.verify(corpus, Math.min(AGREEMENT_CHECK_FILES, corpus.size()), validateUtf8);
report.print(System.out);
if (!report.agree()) {
throw new IllegalStateException("Parsing modes disagree on the first files of the corpus; "
+ "refusing to measure. Run SyntheaBundleVerifier for details.");
}
}
}

@State(Scope.Thread)
public static class ExtractorState {

SyntheaExtractor extractor;

@Setup(Level.Trial)
public void setup(CorpusState corpusState) {
extractor = new SyntheaExtractor(corpusState.corpus.maxLength(), corpusState.validateUtf8);
}
}

@Benchmark
public void domParseOnly(CorpusState corpusState, ExtractorState state, Blackhole blackhole) {
SyntheaCorpus corpus = corpusState.corpus;
SimdJsonParser parser = state.extractor.parser();
for (int i = 0; i < corpus.size(); i++) {
blackhole.consume(parser.parse(corpus.document(i), corpus.length(i)));
}
}

@Benchmark
public long domGetString(CorpusState corpusState, ExtractorState state) {
SyntheaCorpus corpus = corpusState.corpus;
SyntheaExtractor extractor = state.extractor;
extractor.sum().reset();
for (int i = 0; i < corpus.size(); i++) {
extractor.domGetString(corpus.document(i), corpus.length(i));
}
return extractor.sum().checksum();
}

@Benchmark
public long schemaBased(CorpusState corpusState, ExtractorState state) {
SyntheaCorpus corpus = corpusState.corpus;
SyntheaExtractor extractor = state.extractor;
extractor.sum().reset();
for (int i = 0; i < corpus.size(); i++) {
extractor.schemaBased(corpus.document(i), corpus.length(i));
}
return extractor.sum().checksum();
}

@Benchmark
public long domGetBytes(CorpusState corpusState, ExtractorState state) {
SyntheaCorpus corpus = corpusState.corpus;
SyntheaExtractor extractor = state.extractor;
extractor.sum().reset();
for (int i = 0; i < corpus.size(); i++) {
extractor.domGetBytes(corpus.document(i), corpus.length(i));
}
return extractor.sum().checksum();
}

@Benchmark
public long domIndex(CorpusState corpusState, ExtractorState state) {
SyntheaCorpus corpus = corpusState.corpus;
SyntheaExtractor extractor = state.extractor;
extractor.sum().reset();
for (int i = 0; i < corpus.size(); i++) {
extractor.domIndex(corpus.document(i), corpus.length(i));
}
return extractor.sum().checksum();
}

@Benchmark
public long onDemand(CorpusState corpusState, ExtractorState state) {
SyntheaCorpus corpus = corpusState.corpus;
SyntheaExtractor extractor = state.extractor;
extractor.sum().reset();
for (int i = 0; i < corpus.size(); i++) {
extractor.onDemand(corpus.document(i), corpus.length(i));
}
return extractor.sum().checksum();
}
}
Loading