Performance of BeanUtils vs. ReflectionToStringBuilder (for use in Bean classes)

做~自己de王妃 提交于 2019-12-05 06:23:28
jt.

We use ToStringBuilder.reflectionToString() in our objects' toString() methods. We have not had any issues running like this in a production environment. Granted, we rarely use the toString() method.

We also use BeanUtils.describe(), but for another purpose. BeanUtils uses PropertyUtilsBean which keeps an internal cache of beans for which it has performed introspection. It would seem that this would give it a performance advantage over the other, but a little poking around in the reflectionToString source and it seems that since it ultimately relies on the implementation of java.lang.Class, caching comes into play there as well.

Either looks like a viable choice, but BeanUtils.describe() will return a Map of properties where reflectionToString will return a formatted String. I guess it depends on what you want to do with the output.

I would suggest that if your application is heavily dependent on calling toString() on your objects, having a specific implementation might be more beneficial.

Personally, I prefer to generate the toString() method using Eclipse/IntelliJ and then modify it as necessary (only include important fields).

Right click -> Source -> Generate toString(). Select fields. Done.

  1. It takes less time than even writing the Builder code.
  2. It will execute faster.
  3. It doesn't use permgen space (reflection can tend to eat up permgen)

That's the path I would go if you're concerned about performance.

Be careful, as this is reflection based it will be slow.

In a recent web project our Base entity toString() method was ToStringBuilder.reflectionToString(this)

This method is called in hibernate during save (via Spring Data JPA respository). We have quite a large object tree with nested lists, leading to a large in memory and CPU hit during save.

It almost sank the project.

Just use code generator in your IDE to generate toString() method. This way you will avoid the overhead caused by using reflections. In real production system your toString() method can be called very often (100/sec) causing garbage collector to work hard and pause your JVM. These pauses can be seconds or tens of seconds.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!