欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java幾種常用JSON庫性能比較詳解

 更新時間:2019年06月28日 14:17:11   作者:飛污熊博客  
這篇文章主要介紹了Java幾種常用JSON庫性能比較詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

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

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

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

簡單介紹

選擇一個合適的JSON庫要從多個方面進行考慮:

  1. 字符串解析成JSON性能
  2. 字符串解析成JavaBean性能
  3. JavaBean構造JSON性能
  4. 集合構造JSON性能
  5. 易用性

先簡單介紹下四個類庫的身份背景

Gson

項目地址:https://github.com/google/gson

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

FastJson

項目地址:https://github.com/alibaba/fastjson

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

Jackson

項目地址:https://github.com/FasterXML/jackson

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

Jackson優(yōu)點很多:

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

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

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

為什么Jackson的介紹這么長啊?因為它也是本人的最愛。

Json-lib

項目地址:http://json-lib.sourceforge.net/index.html

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

編寫性能測試

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

添加maven依賴

當然首先是添加四個庫的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>

四個庫的工具類

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);
  }
}

準備Model類

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

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序列化性能基準測試

@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("邵同學",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", "秒");

這個是我自己編寫的將性能測試報告數(shù)據(jù)填充至Echarts圖,然后導出png圖片的方法,具體代碼我就不貼了,參考我的github源碼。

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

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

JSON反序列化性能基準測試

@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\":\"邵同學\",\"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í)行后的結果圖:

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Springboot實現(xiàn)動態(tài)定時任務流程詳解

    Springboot實現(xiàn)動態(tài)定時任務流程詳解

    通過重寫SchedulingConfigurer方法實現(xiàn)對定時任務的操作,單次執(zhí)行、停止、啟動三個主要的基本功能,動態(tài)的從數(shù)據(jù)庫中獲取配置的定時任務cron信息,通過反射的方式靈活定位到具體的類與方法中
    2022-09-09
  • SpringCloud?Feign集成AOP的常見問題與解決

    SpringCloud?Feign集成AOP的常見問題與解決

    在使用?Spring?Cloud?Feign?作為微服務通信的工具時,我們可能會遇到?AOP?不生效的問題,這篇文章將深入探討這一問題,給出幾種常見的場景,分析可能的原因,并提供解決方案,希望對大家有所幫助
    2023-10-10
  • Java FileDescriptor總結_動力節(jié)點Java學院整理

    Java FileDescriptor總結_動力節(jié)點Java學院整理

    FileDescriptor 是“文件描述符”??梢员挥脕肀硎鹃_放文件、開放套接字等。接下來通過本文給大家分享Java FileDescriptor總結,感興趣的朋友一起學習吧
    2017-05-05
  • java實現(xiàn)收藏功能

    java實現(xiàn)收藏功能

    這篇文章主要為大家詳細介紹了java實現(xiàn)收藏功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • SpringBoot如何自定義starter

    SpringBoot如何自定義starter

    這篇文章主要介紹了SpringBoot如何自定義starter,Springboot的出現(xiàn)極大的簡化了開發(fā)人員的配置,而這之中的一大利器便是springboot的starter,starter是springboot的核心組成部分,下面來看看集體引用過程吧
    2022-01-01
  • Java Math.round函數(shù)詳解

    Java Math.round函數(shù)詳解

    這篇文章主要介紹了Java Math.round函數(shù)詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • SpringSecurity?Web權限方案實現(xiàn)全過程

    SpringSecurity?Web權限方案實現(xiàn)全過程

    Spring Security是一個功能強大且高度可定制的身份驗證和授權框架,專門用于保護Java應用程序的Web集成,下面這篇文章主要給大家介紹了關于SpringSecurity?Web權限方案實現(xiàn)的相關資料,需要的朋友可以參考下
    2024-01-01
  • 淺析Mybatis 在CS程序中的應用

    淺析Mybatis 在CS程序中的應用

    如果是自己用的Mybatis,不需要考慮對配置文件加密,如果不是,那就需要考慮加密,這篇文章主要講如何配置CS的Mybatis
    2013-07-07
  • 關于bootstrap.yml和bootstrap.properties的優(yōu)先級問題

    關于bootstrap.yml和bootstrap.properties的優(yōu)先級問題

    這篇文章主要介紹了關于bootstrap.yml和bootstrap.properties的優(yōu)先級問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Springboot多種情況yml配置代碼實例

    Springboot多種情況yml配置代碼實例

    這篇文章主要介紹了Springboot多種情況yml配置代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-07-07

最新評論