四种常见json效率比较
因工作需要,在项目中想统一使用同一种json进行解析数据,因此将几种json拿出来比较比较。
第一种 org.json
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
第二种 net.sf.json
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
第三种 com.alibaba.fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency> 第四种 com.google.code.gson
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
实验代码:
public static void main(String args[]){
int data = 1000;
System.out.println("data:"+data);
Long t1 = System.currentTimeMillis();
org.json.JSONObject jsonObject1 = new org.json.JSONObject();
for (int i = 0; i < data; i++) {
jsonObject1.put("k" + i, "v" + i);
}
Long t2 = System.currentTimeMillis();
System.out.println("org.json:" + (t2 - t1));
Long t3 = System.currentTimeMillis();
net.sf.json.JSONObject jsonObject2 = new net.sf.json.JSONObject();
for (int i = 0; i < data; i++) {
jsonObject2.put("k" + i, "v" + i);
}
Long t4 = System.currentTimeMillis();
System.out.println("net.sf.json:" + (t4 - t3));
Long t5 = System.currentTimeMillis();
com.alibaba.fastjson.JSONObject jsonObject3 = new com.alibaba.fastjson.JSONObject();
for (int i = 0; i < data; i++) {
jsonObject3.put("k" + i, "v" + i);
}
Long t6 = System.currentTimeMillis();
System.out.println("com.alibaba.fastjson:" + (t6 - t5));
Long t7 = System.currentTimeMillis();
com.google.gson.JsonObject jsonObject4 = new com.google.gson.JsonObject();
for (int i = 0; i < data; i++) {
jsonObject4.addProperty("k" + i, "v" + i);
}
Long t8 = System.currentTimeMillis();
System.out.println("com.google.gson:" + (t8 - t7));
}
实验结果如下:
data = 1000;
data = 10000;
data = 100000;
data = 1000000;
实验结果:从效率上来讲,当数据量较小时,org.json 处理速度最快,当数据量较大时,com.alibaba.fastjson处理速度最快。
源码分析:
org.json
public JSONObject put(String key, Object value) throws JSONException {
if(key == null) {
throw new NullPointerException("Null key.");
} else {
if(value != null) {
testValidity(value);
this.map.put(key, value);
} else {
this.remove(key);
}
return this;
}
}
com.alibaba.fastjson
public Object put(String key, Object value) {
return this.map.put(key, value);
}
对比源码,显而易见org.json 的 JSONObject 的put()方法,不允许key和value为null,而阿里的fastjson是允许的。
