本篇經過JMH來測試一下Java中幾種常見的JSON解析庫的性能。 每次都在網上看到別人說什麼某某庫性能是如何如何的好,碾壓其餘的庫。可是百聞不如一見,只有本身親手測試過的纔是最值得相信的。html
JSON不論是在Web開發仍是服務器開發中是至關常見的數據傳輸格式,通常狀況咱們對於JSON解析構造的性能並不須要過於關心,除非是在性能要求比較高的系統。java
目前對於Java開源的JSON類庫有不少種,下面咱們取4個經常使用的JSON庫進行性能測試對比, 同時根據測試結果分析若是根據實際應用場景選擇最合適的JSON庫。git
這4個JSON類庫分別爲:Gson,FastJson,Jackson,Json-lib。github
選擇一個合適的JSON庫要從多個方面進行考慮:面試
字符串解析成JSON性能算法
字符串解析成JavaBean性能json
JavaBean構造JSON性能性能優化
集合構造JSON性能服務器
易用性架構
先簡單介紹下四個類庫的身份背景
項目地址:https://github.com/google/gson
Gson是目前功能最全的Json解析神器,Gson當初是爲因應Google公司內部需求而由Google自行研發而來,但自從在2008年五月公開發布初版後已被許多公司或用戶應用。 Gson的應用主要爲toJson與fromJson兩個轉換函數,無依賴,不須要例外額外的jar,可以直接跑在JDK上。 在使用這種對象轉換以前,需先建立好對象的類型以及其成員才能成功的將JSON字符串成功轉換成相對應的對象。 類裏面只要有get和set方法,Gson徹底能夠實現複雜類型的json到bean或bean到json的轉換,是JSON解析的神器。
項目地址:https://github.com/alibaba/fastjson
Fastjson是一個Java語言編寫的高性能的JSON處理器,由阿里巴巴公司開發。無依賴,不須要例外額外的jar,可以直接跑在JDK上。 FastJson在複雜類型的Bean轉換Json上會出現一些問題,可能會出現引用的類型,致使Json轉換出錯,須要制定引用。 FastJson採用首創的算法,將parse的速度提高到極致,超過全部json庫。
項目地址:https://github.com/FasterXML/jackson
Jackson是當前用的比較普遍的,用來序列化和反序列化json的Java開源框架。Jackson社區相對比較活躍,更新速度也比較快, 從Github中的統計來看,Jackson是最流行的json解析器之一,Spring MVC的默認json解析器即是Jackson。
Jackson優勢不少:
Jackson 所依賴的jar包較少,簡單易用。
與其餘 Java 的 json 的框架 Gson 等相比,Jackson 解析大的 json 文件速度比較快。
Jackson 運行時佔用內存比較低,性能比較好
Jackson 有靈活的 API,能夠很容易進行擴展和定製。
目前最新版本是2.9.4,Jackson 的核心模塊由三部分組成:
jackson-core 核心包,提供基於」流模式」解析的相關 API,它包括 JsonPaser 和 JsonGenerator。Jackson 內部實現正是經過高性能的流模式 API 的 JsonGenerator 和 JsonParser 來生成和解析 json。
jackson-annotations 註解包,提供標準註解功能;
jackson-databind 數據綁定包,提供基於」對象綁定」 解析的相關 API( ObjectMapper )和」樹模型」 解析的相關 API(JsonNode);基於」對象綁定」 解析的 API 和」樹模型」解析的 API 依賴基於」流模式」解析的 API。
爲何Jackson的介紹這麼長啊?由於它也是本人的最愛。
項目地址:http://json-lib.sourceforge.net/index.html
json-lib最開始的也是應用最普遍的json解析工具,json-lib 很差的地方確實是依賴於不少第三方包,對於複雜類型的轉換,json-lib對於json轉換成bean還有缺陷, 好比一個類裏面會出現另外一個類的list或者map集合,json-lib從json到bean的轉換就會出現問題。json-lib在功能和性能上面都不能知足如今互聯網化的需求。
接下來開始編寫這四個庫的性能測試代碼。
固然首先是添加四個庫的maven依賴,公平起見,我所有使用它們最新的版本:
1 <!-- Json libs--> 2 <dependency> 3 <groupId>net.sf.json-lib</groupId> 4 <artifactId>json-lib</artifactId> 5 <version>2.4</version> 6 <classifier>jdk15</classifier> 7 </dependency> 8 <dependency> 9 <groupId>com.google.code.gson</groupId> 10 <artifactId>gson</artifactId> 11 <version>2.8.2</version> 12 </dependency> 13 <dependency> 14 <groupId>com.alibaba</groupId> 15 <artifactId>fastjson</artifactId> 16 <version>1.2.46</version> 17 </dependency> 18 <dependency> 19 <groupId>com.fasterxml.jackson.core</groupId> 20 <artifactId>jackson-databind</artifactId> 21 <version>2.9.4</version> 22 </dependency> 23 <dependency> 24 <groupId>com.fasterxml.jackson.core</groupId> 25 <artifactId>jackson-annotations</artifactId> 26 <version>2.9.4</version> 27 </dependency>
FastJsonUtil.java
1 public class FastJsonUtil { 2 public static String bean2Json(Object obj) { 3 return JSON.toJSONString(obj); 4 } 5 6 public static <T> T json2Bean(String jsonStr, Class<T> objClass) { 7 return JSON.parseObject(jsonStr, objClass); 8 } 9 }
GsonUtil.java
1 public class GsonUtil { 2 private static Gson gson = new GsonBuilder().create(); 3 4 public static String bean2Json(Object obj) { 5 return gson.toJson(obj); 6 } 7 8 public static <T> T json2Bean(String jsonStr, Class<T> objClass) { 9 return gson.fromJson(jsonStr, objClass); 10 } 11 12 public static String jsonFormatter(String uglyJsonStr) { 13 Gson gson = new GsonBuilder().setPrettyPrinting().create(); 14 JsonParser jp = new JsonParser(); 15 JsonElement je = jp.parse(uglyJsonStr); 16 return gson.toJson(je); 17 } 18 }
JacksonUtil.java
1 public class JacksonUtil { 2 private static ObjectMapper mapper = new ObjectMapper(); 3 4 public static String bean2Json(Object obj) { 5 try { 6 return mapper.writeValueAsString(obj); 7 } catch (JsonProcessingException e) { 8 e.printStackTrace(); 9 return null; 10 } 11 } 12 13 public static <T> T json2Bean(String jsonStr, Class<T> objClass) { 14 try { 15 return mapper.readValue(jsonStr, objClass); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 return null; 19 } 20 } 21 }
JsonLibUtil.java
1 public class JsonLibUtil { 2 3 public static String bean2Json(Object obj) { 4 JSONObject jsonObject = JSONObject.fromObject(obj); 5 return jsonObject.toString(); 6 } 7 8 @SuppressWarnings("unchecked") 9 public static <T> T json2Bean(String jsonStr, Class<T> objClass) { 10 return (T) JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass); 11 } 12 }
這裏我寫一個簡單的Person類,同時屬性有Date、List、Map和自定義的類FullName,最大程度模擬真實場景。
1 public class Person { 2 private String name; 3 private FullName fullName; 4 private int age; 5 private Date birthday; 6 private List<String> hobbies; 7 private Map<String, String> clothes; 8 private List<Person> friends; 9 10 // getter/setter省略 11 12 @Override 13 public String toString() { 14 StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age=" 15 + age + ", birthday=" + birthday + ", hobbies=" + hobbies 16 + ", clothes=" + clothes + "]n"); 17 if (friends != null) { 18 str.append("Friends:n"); 19 for (Person f : friends) { 20 str.append("t").append(f); 21 } 22 } 23 return str.toString(); 24 } 25 26 }
1 public class FullName { 2 private String firstName; 3 private String middleName; 4 private String lastName; 5 6 public FullName() { 7 } 8 9 public FullName(String firstName, String middleName, String lastName) { 10 this.firstName = firstName; 11 this.middleName = middleName; 12 this.lastName = lastName; 13 } 14 15 // 省略getter和setter 16 17 @Override 18 public String toString() { 19 return "[firstName=" + firstName + ", middleName=" 20 + middleName + ", lastName=" + lastName + "]"; 21 } 22 }
1 @BenchmarkMode(Mode.SingleShotTime) 2 @OutputTimeUnit(TimeUnit.SECONDS) 3 @State(Scope.Benchmark) 4 public class JsonSerializeBenchmark { 5 /** 6 * 序列化次數參數 7 */ 8 @Param({"1000", "10000", "100000"}) 9 private int count; 10 11 private Person p; 12 13 public static void main(String[] args) throws Exception { 14 Options opt = new OptionsBuilder() 15 .include(JsonSerializeBenchmark.class.getSimpleName()) 16 .forks(1) 17 .warmupIterations(0) 18 .build(); 19 Collection<RunResult> results = new Runner(opt).run(); 20 ResultExporter.exportResult("JSON序列化性能", results, "count", "秒"); 21 } 22 23 @Benchmark 24 public void JsonLib() { 25 for (int i = 0; i < count; i++) { 26 JsonLibUtil.bean2Json(p); 27 } 28 } 29 30 @Benchmark 31 public void Gson() { 32 for (int i = 0; i < count; i++) { 33 GsonUtil.bean2Json(p); 34 } 35 } 36 37 @Benchmark 38 public void FastJson() { 39 for (int i = 0; i < count; i++) { 40 FastJsonUtil.bean2Json(p); 41 } 42 } 43 44 @Benchmark 45 public void Jackson() { 46 for (int i = 0; i < count; i++) { 47 JacksonUtil.bean2Json(p); 48 } 49 } 50 51 @Setup 52 public void prepare() { 53 List<Person> friends=new ArrayList<Person>(); 54 friends.add(createAPerson("小明",null)); 55 friends.add(createAPerson("Tony",null)); 56 friends.add(createAPerson("陳小二",null)); 57 p=createAPerson("邵同窗",friends); 58 } 59 60 @TearDown 61 public void shutdown() { 62 } 63 64 private Person createAPerson(String name,List<Person> friends) { 65 Person newPerson=new Person(); 66 newPerson.setName(name); 67 newPerson.setFullName(new FullName("zjj_first", "zjj_middle", "zjj_last")); 68 newPerson.setAge(24); 69 List<String> hobbies=new ArrayList<String>(); 70 hobbies.add("籃球"); 71 hobbies.add("游泳"); 72 hobbies.add("coding"); 73 newPerson.setHobbies(hobbies); 74 Map<String,String> clothes=new HashMap<String, String>(); 75 clothes.put("coat", "Nike"); 76 clothes.put("trousers", "adidas"); 77 clothes.put("shoes", "安踏"); 78 newPerson.setClothes(clothes); 79 newPerson.setFriends(friends); 80 return newPerson; 81 } 82 }
說明一下,上面的代碼中
ResultExporter.exportResult("JSON序列化性能", results, "count", "秒");
這個是我本身編寫的將性能測試報告數據填充至Echarts圖,而後導出png圖片的方法。
執行後的結果圖:
從上面的測試結果能夠看出,序列化次數比較小的時候,Gson性能最好,當不斷增長的時候到了100000,Gson明細弱於Jackson和FastJson, 這時候FastJson性能是真的牛,另外還能夠看到無論數量少仍是多,Jackson一直表現優異。而那個Json-lib簡直就是來搞笑的。^_^
1 @BenchmarkMode(Mode.SingleShotTime) 2 @OutputTimeUnit(TimeUnit.SECONDS) 3 @State(Scope.Benchmark) 4 public class JsonDeserializeBenchmark { 5 /** 6 * 反序列化次數參數 7 */ 8 @Param({"1000", "10000", "100000"}) 9 private int count; 10 11 private String jsonStr; 12 13 public static void main(String[] args) throws Exception { 14 Options opt = new OptionsBuilder() 15 .include(JsonDeserializeBenchmark.class.getSimpleName()) 16 .forks(1) 17 .warmupIterations(0) 18 .build(); 19 Collection<RunResult> results = new Runner(opt).run(); 20 ResultExporter.exportResult("JSON反序列化性能", results, "count", "秒"); 21 } 22 23 @Benchmark 24 public void JsonLib() { 25 for (int i = 0; i < count; i++) { 26 JsonLibUtil.json2Bean(jsonStr, Person.class); 27 } 28 } 29 30 @Benchmark 31 public void Gson() { 32 for (int i = 0; i < count; i++) { 33 GsonUtil.json2Bean(jsonStr, Person.class); 34 } 35 } 36 37 @Benchmark 38 public void FastJson() { 39 for (int i = 0; i < count; i++) { 40 FastJsonUtil.json2Bean(jsonStr, Person.class); 41 } 42 } 43 44 @Benchmark 45 public void Jackson() { 46 for (int i = 0; i < count; i++) { 47 JacksonUtil.json2Bean(jsonStr, Person.class); 48 } 49 } 50 51 @Setup 52 public void prepare() { 53 jsonStr="{"name":"邵同窗","fullName":{"firstName":"zjj_first","middleName":"zjj_middle","lastName":"zjj_last"},"age":24,"birthday":null,"hobbies":["籃球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":[{"name":"小明","fullName":{"firstName":"xxx_first","middleName":"xxx_middle","lastName":"xxx_last"},"age":24,"birthday":null,"hobbies":["籃球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":null},{"name":"Tony","fullName":{"firstName":"xxx_first","middleName":"xxx_middle","lastName":"xxx_last"},"age":24,"birthday":null,"hobbies":["籃球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":null},{"name":"陳小二","fullName":{"firstName":"xxx_first","middleName":"xxx_middle","lastName":"xxx_last"},"age":24,"birthday":null,"hobbies":["籃球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":null}]}"; 54 } 55 56 @TearDown 57 public void shutdown() { 58 } 59 }
執行後的結果圖:
從上面的測試結果能夠看出,反序列化的時候,Gson、Jackson和FastJson區別不大,性能都很優異,而那個Json-lib仍是來繼續搞笑的。
來源:xncoding.com/2018/01/09/java/jsons.html
好文精選