Click here to Skip to main content
13,148,214 members (59,798 online)
Click here to Skip to main content
Add your own
alternative version

Stats

4.8K views
1 bookmarked
Posted 14 Jan 2017

Jsoniter: JSON is faster than thrift/avro

, 14 Jan 2017
Rate this:
Please Sign up or sign in to vote.
Jsoniter is a new JSON library for Java & Go, with innovative API and faster than thrift/avro

Introduction

JSON is considered slow, like several times slower than protobuf/thrift/avro/... 

https://github.com/ngs-doo/dsl-json is a very fast JSON library implemented Java, which proved JSON is not that slow

JSON vs binary 

http://jsoniter.com/ ported dsl-json codegen from .Net to Java (although, dsl-json is a Java library, the codegen is not).  Also added a very sexy "Any" data type to lazy parse any JSON in weakly typed way (which will not be covered in this article, you check it out here)

Serialization speed: https://github.com/json-iterator/jvm-serializers

  • protobuf: 684
  • thrift: 1317
  • avro: 1688
  • dsl-json: 471
  • jsoniter: 517

De-serialization speed: 

  • protobuf: 448
  • thrift: 734
  • avro: 844
  • dsl-json: 776
  • jsoniter: 726

What is the secret of dsl-json that makes JSON even faster than thrift/avro? Isn't text protocol slow?

 

Optimization

there is no JNI or SIMD dark magic. JVM is still not a ideal platform for instruction level customization. Go might be a good choice to try some SIMD, for example: https://github.com/minio/blake2b-simd

the optimization is pretty straight forward

  • allocation less
  • scan only once
  • minimal branching
  • fast path shortcut, optimize for 80% case

Jsoniter ported the implementation of dsl-json, so the following article will be based on jsoniter instead.

Single pass scan

All parsing is done within one pass directly from byte array stream. Single pass has two level of meaning:

  • on the large scale: the iterator api is forward only, you get what you need from current spot. There is no going back.
  • on the micro scale: readInt or readString is done in one pass. For example, parse integer is not done by cutting string out, then parse string. Instead we use the byte stream to calculate int value directly. even readFloat or readDouble is implemented this way, with exceptions.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/IterImplNumber.java

Minimum allocation

Making copy is avoided at all necessary means. For example, the parser has a internal byte array buffer holding recent byte. When parsing the field name of object, we do not allocate new bytes to hold field name. Instead, if possible, the buffer is reused as slice (like go).

Iterator instance itself keep copy of all kinds of buffer it used, and they can be reused by reset iterator with new input instead of create brand new iterator.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/IterImpl.java

Pull from stream

The input can be a InputStream, we do not read all bytes out into a big array. Instead the parsing is done in chunks. When we need more, we pull from the stream.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/IterImplForStreaming.java

Take string seriously

String parsing is performance killer if not being handled properly. The trick I learned from jsonparser and dsljson is taking a fast path for string without escape character.

For java, the string is utf-16 char based. Parsing utf8 byte stream to utf16 char array is done by the parser directly, instead of using UTF8 charset. The cost of construct string, is simplely a char array copy.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/IterImplString.java

Covert string back into bytes is also slow. If we are sure the string is ascii only, there is faster way to do that using getBytes

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/output/JsonStream.java

Schema based

Iterator api is active instead of passive compared to tokenizer api. It does not parse the token out, then if branching. Instead, given the schema, we know exactly what is ahead of us, so we just parse them as what we think it should be. If input disagree, then we raise proper error.

If data binding is done using codegen mode, the whole decoder/encoder source code will be generated. We know exactly what to write first, what to write second. What to expect next. 

example generated code: https://github.com/json-iterator/java/blob/master/demo/src/main/java/encoder/com/jsoniter/demo/User.java

Skip should take different path

Skip an object or array should take different path learned from jsonparser. We do not care about nested field name or so when we are skipping a whole object.

This area can be furthur improved in language support SIMD: https://github.com/kostya/benchmarks/pull/46#issuecomment-147932489

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/IterImplSkip.java

Table lookup

Some calculation such as what is int value for char ‘5’ can be done ahead of time.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/IterImplNumber.java

Match field by hash

Most part of JSON parsing can be pre-defined by providing a class as the schema. However, there is no ordering of field names in JSON. So there must be a lot of branching when matching field. The trick used in dsl-json is hashcode. Instead of comparing field name string by string, it calculates the hash of field and do a switch-case lookup

Match field by trie-tree

hashcode is not collison free. We can add string equals after hashcode match, or we can do this

<code>public Object decode(java.lang.reflect.Type type, com.jsoniter.Jsoniter iter) {
        com.jsoniter.SimpleObject obj = new com.jsoniter.SimpleObject();
        for (com.jsoniter.Slice field = iter.readObjectAsSlice(); field != null; field = iter.readObjectAsSlice()) {
            switch (field.len) {
                case 6:
                    if (field.at(0)==102) {
                        if (field.at(1)==105) {
                            if (field.at(2)==101) {
                                if (field.at(3)==108) {
                                    if (field.at(4)==100) {
                                        if (field.at(5)==49) {
                                            obj.field1 = iter.readString();
                                            continue;
                                        }
                                        if (field.at(5)==50) {
                                            obj.field2 = iter.readString();
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;
            }
            iter.skip();
        }
        return obj;
    }
}</code>

Shortcut path

We know most string is ascii, so we can try to decode it as if its only ascii first. If it is not the case, we fallback to slower way.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/IterImplString.java

Lazy parsing

If read JSON into Object or JsonNode, we read all the fields and elements. It will allocate a lot of memory and doing a lot of computation. If we can deserialize only when we have to, the lazy parsing can save lot of unnecessary work.

This is the core idea behind "Any" data type. It essentially makes the forward only json-iterator random accessable.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/any/ObjectLazyAny.java

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/any/ArrayLazyAny.java

Write as much as we can in one call

One important optimization in JSON serialization is do not write byte by byte. write("{\"field1\":") is faster than write('{'), write("field1") then write(':')

If we know some field is not-nullable, we can combine its quote or [] into the one write call.

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/output/CodegenResult.java

Faster number codec

SIMD can make this faster as well, sadly Java does not have it. But faster implementation than Integer.toString and Integer.valueOf is possible

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/output/StreamImplNumber.java

Dynamic class shadowing

The input can be byte array or input stream. The decoding can be greatly simplified if only limted byte to process. However, we can not assume we only process byte array. Normally, we would use virtual method to solve this problem. However, runtime dispatching via vtable is slow. 

Like c++ template, Java has class and class loader to achive zero-cost abstraction. The class loading process can be injected with different class. We implement two class, one IterImpl.class one IterImplForStreaming.class. At runtime, we decide which one is the one to use through class shadowing. 

related source code: https://github.com/json-iterator/java/blob/master/src/main/java/com/jsoniter/DynamicCodegen.java

Summary

don't get me wrong, JSON is a slower text protocol than binary protocols. JSON implemention and binary protocol implementation is a different story. Without careful optimization, binary protocol can be slower, even in theory it should be much faster. With current implementation in Java world, other options is not "significantly" faster than JSON. 

Java is missing the SIMD support, which makes me wonder will SIMD makes JSON faster? will SIMD make protobuf/thrit/avro even faster? Go can be really good language try things out. Looking forward to that.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

taowen
China China
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170924.2 | Last Updated 14 Jan 2017
Article Copyright 2017 by taowen
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid