Performance¶
Generated copiers¶
A class copied by its fields gets a generated copier the first time it is copied: a class which reads and writes the fields directly, without reflection and without a loop over field adapters. Final fields are written by method handles (JDK 16+) or by the toolset. The copiers are generated by the ClassFile API on JDK 24+ and by ASM on older JDKs, if ASM is on the classpath, see Dependencies:
Generated copiers are enabled by default and shared by the cloners with the same field policies; classes which cannot
get one (e.g. JDK classes, or classes whose class loader does not see the cloner) are copied as usual.
Cloners.builder().generatedCopiers(false) disables them.
In the benchmark of the project (MechanismsBenchmark, a list of 1000 orders with 10 lines each, JDK 25) a clone
takes 1.4 ms with generated copiers, whatever the field access, 1.6 ms by fields with Unsafe field access, 2.2 ms by
fields with reflection or var handles. Narcissus accesses fields by native calls: 80 ms by fields, 2.3 ms with
generated copiers.
Other libraries¶
ClonersBenchmark compares the default cloner with Kryo (copy(), with
reference tracking, so shared objects and cycles are kept as the cloner keeps them),
Cloning and Java serialization to a byte array and back. Three graphs: 1000
orders of own classes with 10 lines each, a large random graph of JDK types (collections, maps, arrays, boxed values,
dates), a small one of them for the cost of a call. Time of a clone, JMH, Intel Core i7-7700:
| Library | Orders, JDK 17 | Orders, JDK 25 | JDK types, JDK 17 | JDK types, JDK 25 | Small, JDK 17 | Small, JDK 25 |
|---|---|---|---|---|---|---|
| the cloner | 1.34 ms | 1.40 ms | 8.5 ms | 8.9 ms | 4.0 us | 4.0 us |
| Kryo | 2.33 ms | 1.90 ms | 14.4 ms | 15.1 ms | 5.0 us | 3.4 us |
| Cloning | 1.80 ms | 1.78 ms | 13.0 ms | 18.2 ms | 8.4 us | 8.8 us |
| serialization | 9.39 ms | 8.04 ms | 46.4 ms | 45.8 ms | 107 us | 101 us |
The cloner is the fastest on graphs; on a small graph Kryo on JDK 25 is ahead by a fraction of a microsecond, the
cost of the context of a clone. Serialization is 5-27 times slower than the cloner and needs Serializable classes.
How to run the benchmarks is told in
CONTRIBUTING.
Copy constructors¶
The build tools add copy constructors to the classes you list. Such a class is cloned by new: final
fields are written directly, no allocator is needed. They are used when the field policy copies all fields of the
class by default; Cloners.builder().copyConstructors(false) disables them.
Tips¶
- Build a cloner once and reuse it: its caches of copiers live as long as the cloner.
- Prefer type and field actions to object actions and object policies, which are asked for every object.
- Share what does not need copying:
CopyAction.ORIGINALfor types of immutable values the cloner does not know,singleton()for well-known instances. - The parallel mode pays off only for large graphs.