Search code examples
javaserializationkryo

What is the core technology of kryo?


Kryo is really fast and small. what's the secret here?

I have diving into its code for a while, but still need some guidance.

Thanks.


Solution

  • From their page:

    The 2.22 release fixes many reported issues and improves stability and performance. It also introduces a number of new features, most notably that it can use Unsafe to read and write object memory directly. This is the absolute fastest way to do serialization, especially for large primitive arrays.

    It uses direct bytecode-level access to the fields - sun.misc.Unsafe or ASM library. Kryo was fast even before introducing unsafe usage. The general answer, I think, is that performance is their highest priority. Java's reflection is not that slow when used carefully - i.e. when the java.lang.Field and java.lang.Method are cached. I set up an experiment which sorted an array with two different comparators - one was using direct field access and the other was using cached fields. There was only 2x difference, which means unnoticeable in context with IO.

    FieldSerializer:

    By default, most classes will end up using FieldSerializer. It essentially does what hand written serialization would, but does it automatically. FieldSerializer does direct assignment to the object's fields. If the fields are public, protected, or default access (package private), bytecode generation is used for maximum speed (see ReflectASM). For private fields, setAccessible and cached reflection is used, which is still quite fast.