<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Java幾種常用 JSON 庫性能比較,哪家最強(qiáng)?

          共 20758字,需瀏覽 42分鐘

           ·

          2022-11-01 11:59

          點(diǎn)擊藍(lán)色“程序員黃小斜”關(guān)注我喲

          加個(gè)“星標(biāo)”,每天和你一起多進(jìn)步一點(diǎn)點(diǎn)!


          簡單介紹

            • Gson
            • FastJson
            • Jackson
            • Json-lib
            • 編寫性能測試
            • 添加maven依賴
            • 四個(gè)庫的工具類
            • 準(zhǔn)備Model類
            • JSON序列化性能基準(zhǔn)測試
            • JSON反序列化性能基準(zhǔn)測試

          本篇通過JMH來測試一下Java中幾種常見的JSON解析庫的性能。每次都在網(wǎng)上看到別人說什么某某庫性能是如何如何的好,碾壓其他的庫。但是百聞不如一見,只有自己親手測試過的才是最值得相信的。

          JSON不管是在Web開發(fā)還是服務(wù)器開發(fā)中是相當(dāng)常見的數(shù)據(jù)傳輸格式,一般情況我們對于JSON解析構(gòu)造的性能并不需要過于關(guān)心,除非是在性能要求比較高的系統(tǒng)。

          目前對于Java開源的JSON類庫有很多種,下面我們?nèi)?個(gè)常用的JSON庫進(jìn)行性能測試對比, 同時(shí)根據(jù)測試結(jié)果分析如果根據(jù)實(shí)際應(yīng)用場景選擇最合適的JSON庫。

          這4個(gè)JSON類庫分別為:Gson,F(xiàn)astJson,Jackson,Json-lib。

          簡單介紹

          選擇一個(gè)合適的JSON庫要從多個(gè)方面進(jìn)行考慮:

          • 字符串解析成JSON性能
          • 字符串解析成JavaBean性能
          • JavaBean構(gòu)造JSON性能
          • 集合構(gòu)造JSON性能
          • 易用性

          先簡單介紹下四個(gè)類庫的身份背景

          Gson

          項(xiàng)目地址:https://github.com/google/gson

          Gson是目前功能最全的Json解析神器,Gson當(dāng)初是為因應(yīng)Google公司內(nèi)部需求而由Google自行研發(fā)而來,但自從在2008年五月公開發(fā)布第一版后已被許多公司或用戶應(yīng)用。Gson的應(yīng)用主要為toJson與fromJson兩個(gè)轉(zhuǎn)換函數(shù),無依賴,不需要例外額外的jar,能夠直接跑在JDK上。在使用這種對象轉(zhuǎn)換之前,需先創(chuàng)建好對象的類型以及其成員才能成功的將JSON字符串成功轉(zhuǎn)換成相對應(yīng)的對象。類里面只要有g(shù)et和set方法,Gson完全可以實(shí)現(xiàn)復(fù)雜類型的json到bean或bean到j(luò)son的轉(zhuǎn)換,是JSON解析的神器。

          FastJson

          項(xiàng)目地址:https://github.com/alibaba/fastjson

          Fastjson是一個(gè)Java語言編寫的高性能的JSON處理器,由阿里巴巴公司開發(fā)。無依賴,不需要例外額外的jar,能夠直接跑在JDK上。FastJson在復(fù)雜類型的Bean轉(zhuǎn)換Json上會(huì)出現(xiàn)一些問題,可能會(huì)出現(xiàn)引用的類型,導(dǎo)致Json轉(zhuǎn)換出錯(cuò),需要制定引用。FastJson采用獨(dú)創(chuàng)的算法,將parse的速度提升到極致,超過所有json庫。

          Jackson

          項(xiàng)目地址:https://github.com/FasterXML/jackson

          Jackson是當(dāng)前用的比較廣泛的,用來序列化和反序列化json的Java開源框架。Jackson社區(qū)相對比較活躍,更新速度也比較快, 從Github中的統(tǒng)計(jì)來看,Jackson是最流行的json解析器之一,Spring MVC的默認(rèn)json解析器便是Jackson。

          Jackson優(yōu)點(diǎn)很多:

          • Jackson 所依賴的jar包較少,簡單易用。
          • 與其他 Java 的 json 的框架 Gson 等相比,Jackson 解析大的 json 文件速度比較快。
          • Jackson 運(yùn)行時(shí)占用內(nèi)存比較低,性能比較好
          • Jackson 有靈活的 API,可以很容易進(jìn)行擴(kuò)展和定制。

          目前最新版本是2.9.4,Jackson 的核心模塊由三部分組成:

          1. jackson-core 核心包,提供基于”流模式”解析的相關(guān) API,它包括 JsonPaser 和 JsonGenerator。Jackson 內(nèi)部實(shí)現(xiàn)正是通過高性能的流模式 API 的 JsonGenerator 和 JsonParser 來生成和解析 json。
          2. jackson-annotations 注解包,提供標(biāo)準(zhǔn)注解功能;
          3. jackson-databind 數(shù)據(jù)綁定包,提供基于”對象綁定” 解析的相關(guān) API( ObjectMapper )和”樹模型” 解析的相關(guān) API(JsonNode);基于”對象綁定” 解析的 API 和”樹模型”解析的 API 依賴基于”流模式”解析的 API。

          為什么Jackson的介紹這么長???因?yàn)樗彩潜救说淖類邸?/p>

          Json-lib

          項(xiàng)目地址:http://json-lib.sourceforge.net/index.html

          json-lib最開始的也是應(yīng)用最廣泛的json解析工具,json-lib 不好的地方確實(shí)是依賴于很多第三方包,對于復(fù)雜類型的轉(zhuǎn)換,json-lib對于json轉(zhuǎn)換成bean還有缺陷, 比如一個(gè)類里面會(huì)出現(xiàn)另一個(gè)類的list或者map集合,json-lib從json到bean的轉(zhuǎn)換就會(huì)出現(xiàn)問題。json-lib在功能和性能上面都不能滿足現(xiàn)在互聯(lián)網(wǎng)化的需求。

          編寫性能測試

          接下來開始編寫這四個(gè)庫的性能測試代碼。

          添加maven依賴

          當(dāng)然首先是添加四個(gè)庫的maven依賴,公平起見,我全部使用它們最新的版本:

          <!-- Json libs-->
          <dependency>
              <groupId>net.sf.json-lib</groupId>
              <artifactId>json-lib</artifactId>
              <version>2.4</version>
              <classifier>jdk15</classifier>
          </dependency>
          <dependency>
              <groupId>com.google.code.gson</groupId>
              <artifactId>gson</artifactId>
              <version>2.8.2</version>
          </dependency>
          <dependency>
              <groupId>com.alibaba</groupId>
              <artifactId>fastjson</artifactId>
              <version>1.2.46</version>
          </dependency>
          <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-databind</artifactId>
              <version>2.9.4</version>
          </dependency>
          <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-annotations</artifactId>
              <version>2.9.4</version>
          </dependency>

          四個(gè)庫的工具類

          FastJsonUtil.java

          public class FastJsonUtil {
              public static String bean2Json(Object obj) {
                  return JSON.toJSONString(obj);
              }

              public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
                  return JSON.parseObject(jsonStr, objClass);
              }
          }

          GsonUtil.java

          public class GsonUtil {
              private static Gson gson = new GsonBuilder().create();

              public static String bean2Json(Object obj) {
                  return gson.toJson(obj);
              }

              public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
                  return gson.fromJson(jsonStr, objClass);
              }

              public static String jsonFormatter(String uglyJsonStr) {
                  Gson gson = new GsonBuilder().setPrettyPrinting().create();
                  JsonParser jp = new JsonParser();
                  JsonElement je = jp.parse(uglyJsonStr);
                  return gson.toJson(je);
              }
          }

          JacksonUtil.java

          public class JacksonUtil {
              private static ObjectMapper mapper = new ObjectMapper();

              public static String bean2Json(Object obj) {
                  try {
                      return mapper.writeValueAsString(obj);
                  } catch (JsonProcessingException e) {
                      e.printStackTrace();
                      return null;
                  }
              }

              public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
                  try {
                      return mapper.readValue(jsonStr, objClass);
                  } catch (IOException e) {
                      e.printStackTrace();
                      return null;
                  }
              }
          }

          JsonLibUtil.java

          public class JsonLibUtil {

              public static String bean2Json(Object obj) {
                  JSONObject jsonObject = JSONObject.fromObject(obj);
                  return jsonObject.toString();
              }

              @SuppressWarnings("unchecked")
              public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
                  return (T) JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass);
              }
          }

          準(zhǔn)備Model類

          這里我寫一個(gè)簡單的Person類,同時(shí)屬性有Date、List、Map和自定義的類FullName,最大程度模擬真實(shí)場景。

          public class Person {
              private String name;
              private FullName fullName;
              private int age;
              private Date birthday;
              private List<String> hobbies;
              private Map<String, String> clothes;
              private List<Person> friends;

              // getter/setter省略

              @Override
              public String toString() {
                  StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age="
                          + age + ", birthday=" + birthday + ", hobbies=" + hobbies
                          + ", clothes=" + clothes + "]\n");
                  if (friends != null) {
                      str.append("Friends:\n");
                      for (Person f : friends) {
                          str.append("\t").append(f);
                      }
                  }
                  return str.toString();
              }

          }
          public class FullName {
              private String firstName;
              private String middleName;
              private String lastName;

              public FullName() {
              }

              public FullName(String firstName, String middleName, String lastName) {
                  this.firstName = firstName;
                  this.middleName = middleName;
                  this.lastName = lastName;
              }

              // 省略getter和setter

              @Override
              public String toString() {
                  return "[firstName=" + firstName + ", middleName="
                          + middleName + ", lastName=" + lastName + "]";
              }
          }

          JSON序列化性能基準(zhǔn)測試

          @BenchmarkMode(Mode.SingleShotTime)
          @OutputTimeUnit(TimeUnit.SECONDS)
          @State(Scope.Benchmark)
          public class JsonSerializeBenchmark {
              /**
               * 序列化次數(shù)參數(shù)
               */
              @Param({"1000""10000""100000"})
              private int count;

              private Person p;

              public static void main(String[] args) throws Exception {
                  Options opt = new OptionsBuilder()
                          .include(JsonSerializeBenchmark.class.getSimpleName())
                          .forks(1)
                          .warmupIterations(0)
                          .build();
                  Collection<RunResult> results =  new Runner(opt).run();
                  ResultExporter.exportResult("JSON序列化性能", results, "count""秒");
              }

              @Benchmark
              public void JsonLib() {
                  for (int i = 0; i < count; i++) {
                      JsonLibUtil.bean2Json(p);
                  }
              }

              @Benchmark
              public void Gson() {
                  for (int i = 0; i < count; i++) {
                      GsonUtil.bean2Json(p);
                  }
              }

              @Benchmark
              public void FastJson() {
                  for (int i = 0; i < count; i++) {
                      FastJsonUtil.bean2Json(p);
                  }
              }

              @Benchmark
              public void Jackson() {
                  for (int i = 0; i < count; i++) {
                      JacksonUtil.bean2Json(p);
                  }
              }

              @Setup
              public void prepare() {
                  List<Person> friends=new ArrayList<Person>();
                  friends.add(createAPerson("小明",null));
                  friends.add(createAPerson("Tony",null));
                  friends.add(createAPerson("陳小二",null));
                  p=createAPerson("邵同學(xué)",friends);
              }

              @TearDown
              public void shutdown() {
              }

              private Person createAPerson(String name,List<Person> friends) {
                  Person newPerson=new Person();
                  newPerson.setName(name);
                  newPerson.setFullName(new FullName("zjj_first""zjj_middle""zjj_last"));
                  newPerson.setAge(24);
                  List<String> hobbies=new ArrayList<String>();
                  hobbies.add("籃球");
                  hobbies.add("游泳");
                  hobbies.add("coding");
                  newPerson.setHobbies(hobbies);
                  Map<String,String> clothes=new HashMap<String, String>();
                  clothes.put("coat""Nike");
                  clothes.put("trousers""adidas");
                  clothes.put("shoes""安踏");
                  newPerson.setClothes(clothes);
                  newPerson.setFriends(friends);
                  return newPerson;
              }
          }

          說明一下,上面的代碼中

          ResultExporter.exportResult("JSON序列化性能", results, "count""秒");

          這個(gè)是我自己編寫的將性能測試報(bào)告數(shù)據(jù)填充至Echarts圖,然后導(dǎo)出png圖片的方法。

          執(zhí)行后的結(jié)果圖:

          圖片

          從上面的測試結(jié)果可以看出,序列化次數(shù)比較小的時(shí)候,Gson性能最好,當(dāng)不斷增加的時(shí)候到了100000,Gson明細(xì)弱于Jackson和FastJson, 這時(shí)候FastJson性能是真的牛,另外還可以看到不管數(shù)量少還是多,Jackson一直表現(xiàn)優(yōu)異。而那個(gè)Json-lib簡直就是來搞笑的。^_^

          JSON反序列化性能基準(zhǔn)測試

          @BenchmarkMode(Mode.SingleShotTime)
          @OutputTimeUnit(TimeUnit.SECONDS)
          @State(Scope.Benchmark)
          public class JsonDeserializeBenchmark {
              /**
               * 反序列化次數(shù)參數(shù)
               */
              @Param({"1000""10000""100000"})
              private int count;

              private String jsonStr;

              public static void main(String[] args) throws Exception {
                  Options opt = new OptionsBuilder()
                          .include(JsonDeserializeBenchmark.class.getSimpleName())
                          .forks(1)
                          .warmupIterations(0)
                          .build();
                  Collection<RunResult> results =  new Runner(opt).run();
                  ResultExporter.exportResult("JSON反序列化性能", results, "count""秒");
              }

              @Benchmark
              public void JsonLib() {
                  for (int i = 0; i < count; i++) {
                      JsonLibUtil.json2Bean(jsonStr, Person.class);
                  }
              }

              @Benchmark
              public void Gson() {
                  for (int i = 0; i < count; i++) {
                      GsonUtil.json2Bean(jsonStr, Person.class);
                  }
              }

              @Benchmark
              public void FastJson() {
                  for (int i = 0; i < count; i++) {
                      FastJsonUtil.json2Bean(jsonStr, Person.class);
                  }
              }

              @Benchmark
              public void Jackson() {
                  for (int i = 0; i < count; i++) {
                      JacksonUtil.json2Bean(jsonStr, Person.class);
                  }
              }

              @Setup
              public void prepare() {
                  jsonStr="{\"name\":\"邵同學(xué)\",\"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}]}";
              }

              @TearDown
              public void shutdown() {
              }
          }

          執(zhí)行后的結(jié)果圖:

          圖片

          從上面的測試結(jié)果可以看出,反序列化的時(shí)候,Gson、Jackson和FastJson區(qū)別不大,性能都很優(yōu)異,而那個(gè)Json-lib還是來繼續(xù)搞笑的。

          鏈接:https://xncoding.com/2018/01/09/java/jsons.html

          1億條數(shù)據(jù)批量插入 MySQL,哪種方式最快?


          Java反射和new效率對比,差距有多大?


          源碼被外包誤上傳到 GitHub,豐田近 30 萬數(shù)據(jù)遭泄露?


          — 【 THE END 】—
          公眾號[程序員黃小斜]全部博文已整理成一個(gè)目錄,請?jiān)诠娞柪锘貜?fù)「m」獲??!

          最近面試BAT,整理一份面試資料Java面試BATJ通關(guān)手冊,覆蓋了Java核心技術(shù)、JVM、Java并發(fā)、SSM、微服務(wù)、數(shù)據(jù)庫、數(shù)據(jù)結(jié)構(gòu)等等。

          獲取方式:點(diǎn)“在看”,關(guān)注公眾號并回復(fù) PDF 領(lǐng)取,更多內(nèi)容陸續(xù)奉上。

          文章有幫助的話,在看,轉(zhuǎn)發(fā)吧。

          謝謝支持喲 (*^__^*)

          瀏覽 65
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲家庭乱轮五月天 | 四虎av | 蜜桃臀美女被操 | 東方在线成人AⅤ | 特级无码一区二区三区 |