简体   繁体   中英

Performant way of nullifying all fields of an object

I have a simple pojo class with 20+ fields and performance-sensitive piece of code. To reduce allocations I reuse the same instance of the class. How to clean-up the object the most performant (unsafe) way?

If I'm not mistaking fields data is stored as a continuous sequence of bytes so I expect that there must be something as fast as System.arraycopy .

The class itself is a part of a stable API and not a subject to modify.

Calling 20 simple setters is a cheap operation. It takes just a several nanoseconds. I'm pretty sure it's not the thing that worth optimizing.

Setting fields one by one in a straightforward way is already enough optimized. In theory, it is possible to clear an object a little bit faster with SIMD instructions, but there is no way to do it in Java.

There is a method Unsafe.setMemory , but it works only for primitive arrays. This limitation is quite understood: it's not valid to clear an object with reference fields with a bulk operation, because different GCs might need to track updates to reference fields individually.

If you look at Arrays.fill implementation, it uses a simple loop that stores elements one by one, and the method is not even a JVM instrinsic for above reasons.

As already mentioned the reasoning behind it is highly questionable.

We don't want to use reflection since it's known to be quite slow. Would you consider using a Java bytecode manipulation library (Javassist, Bytebuddy, ..) which allows you to modify the Pojo class and add an additional method which will directly set all the fields to null .

Assuming you want to nullify all fields at once always, then the easiest way would be to have an internal object that holds all the values. Have your getters and setters be light wrappers around the fields of that object. Then instead of nullifying the fields individually, just refresh the inner object with a new instance where the fields start as null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM