最近对自己写的elasticsearch客户端框架在进行性能优化,数据插入部分使用的是JAVABean对象方式传参,框架内部使用了fastjson进行对象转json字符串的操作,尝试着使用不同方式进行对象转json字符串操作。找到了一种性能更好的方式,具体请看下面代码段:
package test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import java.lang.reflect.Field; import java.util.List; / * Created by memory_fu on 2021/1/7. */ public class ReflectasmTest { public static void main(String[] args) throws IllegalAccessException { Person person = new Person(); person.setAge(10); person.setId("1"); person.setName("傅浩"); person.setHobby("ball"); int sumCount = ;// 循环次数 long l1 = System.currentTimeMillis(); for (int i = 0; i < sumCount; i++) { testFastJSON(person); } System.out.println("fastjson方式转换=====: " + (System.currentTimeMillis() - l1) + " ms."); long l2 = System.currentTimeMillis(); for (int i = 0; i < sumCount; i++) { testReflection(person); } System.out.println("JAVA反射方式转换=====: " + (System.currentTimeMillis() - l2) + " ms."); } / * 方式一: * fastjson 对象转为JSON字符串 */ public static
void testFastJSON(T vo) throws IllegalAccessException { String string = JSON.toJSONString(vo); JSONObject jsonObject = JSON.parseObject(string); String str = jsonObject.toJSONString(); // System.out.println(str); } public static List
fields = null; / * 反射方式拿到类的field集合 */ public static
List
init(T vo) { Class
aClass = vo.getClass(); fields = Lists.newArrayList(); for (Class i = aClass; i != Object.class; i = i.getSuperclass()) { Field[] declaredFields = i.getDeclaredFields(); for (Field field : declaredFields) { fields.add(field); } } return fields; } / * 方式二: * 反射方式 对象转为JSON字符串 */ public static
void testReflection(T vo) throws IllegalAccessException { if (fields == null) { init(vo); } JSONObject jsonObject = new JSONObject(); for (Field field : fields) { jsonObject.put(field.getName(), field.get(vo)); } String str = jsonObject.toJSONString(); // System.out.println(str); } }
基于2000万数据进行测试结果:
可以明显看出使用JAVA反射方式性能比使用fastjson要高,具体原因是因为fastjson转换内部有很多数据格式校验,而我们使用反射方式没有这些校验,所以性能提升明显。
结论: 对于业务开发过程中,要进行性能优化并且对数据内容格式已知情况下,可使用 方式二 进行定制性优化。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/225868.html原文链接:https://javaforall.net
