以下使用两个都是alibaba的json转换工具,在无意中发现在使用map转换字符串的时候效率有很大的区别。
com.alibaba.fastjson.JSON.toJSONString
com.alibaba.druid.support.json.JSONUtils.toJSONString
测试代码
@Test
public void testMap2JsonStr() throws Exception {
Object map = new MfResponse();
long l = System.currentTimeMillis();
com.alibaba.fastjson.JSON.toJSONString(map);
long end = System.currentTimeMillis() - l;
System.out.println("com.alibaba.fastjson.JSON.toJSONString用时:" + end + "ms");
l = System.currentTimeMillis();
com.alibaba.druid.support.json.JSONUtils.toJSONString(map);
end = System.currentTimeMillis() - l;
System.out.println("com.alibaba.druid.support.json.JSONUtils.toJSONString用时:" + end + "ms");
}
执行结果
com.alibaba.fastjson.JSON.toJSONString用时:210ms
com.alibaba.druid.support.json.JSONUtils.toJSONString用时:3ms
问题:
虽然druid中提供的JSONUtils执行效率高,但只能支持普通类型的转换。以下是JSONUtils工具类中的某个方法
public void writeObject(Object o) {
if (o == null) {
this.writeNull();
} else if (o instanceof String) {
this.writeString((String)o);
} else if (o instanceof Number) {
this.write(o.toString());
} else if (o instanceof Boolean) {
this.write(o.toString());
} else if (o instanceof Date) {
this.writeDate((Date)o);
} else if (o instanceof Collection) {
this.writeArray((Collection)o);
} else if (o instanceof Throwable) {
this.writeError((Throwable)o);
} else {
int i;
if (o instanceof int[]) {
int[] array = (int[])((int[])o);
this.write('[');
for(i = 0; i < array.length; ++i) {
if (i != 0) {
this.write(',');
}
this.write(array[i]);
}
this.write(']');
} else if (o instanceof long[]) {
long[] array = (long[])((long[])o);
this.write('[');
for(i = 0; i < array.length; ++i) {
if (i != 0) {
this.write(',');
}
this.write(array[i]);
}
this.write(']');
} else if (o instanceof TabularData) {
this.writeTabularData((TabularData)o);
} else if (o instanceof CompositeData) {
this.writeCompositeData((CompositeData)o);
} else if (o instanceof Map) {
this.writeMap((Map)o);
} else {
throw new IllegalArgumentException("not support type : " + o.getClass());
}
}
}