测试环境:jar包gson2.7、fastjson1.2.15,系统win10_64
HashMap<String, String> hashMap = new HashMap<>();
for (int i = 0; i < 1000; i++) {
hashMap.put("key" + i, "value" + i);
}
// gson方式生成json字符串
long start = System.currentTimeMillis();
String json = new Gson().toJson(hashMap);
System.out.println("gson生成字符串用时:" + (System.currentTimeMillis() - start));
System.out.println(json);
System.out.println("-----------------------------------------");
// fastjson方式生成json字符串
start = System.currentTimeMillis();
json = JSON.toJSONString(hashMap);
System.out.println("fastjson生成字符串用时:" + (System.currentTimeMillis() - start));
System.out.println(json);
System.out.println("-----------------------------------------");
Type type1 = new TypeToken<HashMap<String, String>>() {
}.getType();
start = System.currentTimeMillis();
Map<String, String> userMap = new Gson().fromJson(json, type1);
System.out.println("gson解析字符串用时:" + (System.currentTimeMillis() - start));
System.out.println(userMap.toString());
TypeReference<Map<String, String>> typeReference = new TypeReference<Map<String, String>>() {
};
start = System.currentTimeMillis();
Map<String, String> userMap2 = JSON.parseObject(json, typeReference);
System.out.println("fastjson解析字符串用时:" + (System.currentTimeMillis() - start));
System.out.println(userMap2.toString());
先测试了1000对数据,结果:
gson生成字符串用时:86
-----------------------------------------
fastjson生成字符串用时:63
-----------------------------------------
gson解析字符串用时:7
fastjson解析字符串用时:37
又测试了100万对数据,结果:
gson生成字符串用时:512
-----------------------------------------
fastjson生成字符串用时:986
-----------------------------------------
gson解析字符串用时:1018
fastjson解析字符串用时:2985
当测试1000万对数据的时候,gson长时间无响应,fastjson报出outOfMemery异常
综上,在数据量100万对以内数据的时候,gson的生成字符串速度,由比fastjson慢逐渐变得比fastjson快。而在解析数据上,gson是比fastjson快的,跟网上大部分文章说的不符。以上结论纯以测试结果,如果有问题,欢迎指出。