Source: www.xncoding.com/2018/01/09/java/jsons.html
Benpian by JMH to test the performance of Java in several common JSON parsing library. Every time the Internet to see what people say so and so database performance is how how good, rolling other libraries. But seeing is believing, only tested their own hands is the most worthy of belief.
JSON is either in development or Web server developed quite common data transmission format, we generally constructed for JSON parsing performance does not need to be too concerned, except in the high performance requirements of the system.
There are open-source JSON for Java class libraries are many, let's take the four commonly used JSON library performance test comparison, but based on analysis of test results if you choose the most appropriate JSON library based on the actual application scenarios.
This four JSON library are: Gson, FastJson, Jackson, Json-lib.
basic introduction
Select an appropriate JSON library from multiple aspects to consider:
-
String to parse performance JSON
-
String to parse performance JavaBean
-
JSON structure JavaBean properties
-
JSON construct the set of performance
-
Ease of use
Briefly explain the context of the identity of the four libraries
Gson
Project address: https: //github.com/google/gson
Gson is the most versatile Json parsing artifact, Gson Initially, it was to cope with domestic demand while Google's own R & D evolved from Google, but since publicly released the first edition in May 2008 the company has been a lot of users or applications. Gson application mainly fromJson toJson with two conversion functions, no dependency, no additional JAR exceptions, can be run directly on the JDK. Before using this object conversion, you must first create a good object types and their members can successfully be successfully converted into the corresponding JSON string object. As long as the class which get and set methods, can achieve Gson json to complex type of bean to bean or json conversion is JSON parsing artifact.
FastJson
Project address: https: //github.com/alibaba/fastjson
Fastjson Java language is written in a high-performance JSON processor, developed by Alibaba. No dependence, no additional jar exception, can be directly run on JDK. FastJson will appear on a complex type of Bean convert Json some of the problems, the type of reference may occur, resulting Json conversion error, the need for reference. FastJson using original algorithm, we will parse the speed to the extreme, more than all the json library.
Jackson
Project address: https: //github.com/FasterXML/jackson
Jackson is currently more widely used for serialization and deserialization json open-source Java framework. Jackson community is relatively active, the speed is faster, Github from the statistical point of view, Jackson is one of the most popular json parser, Spring MVC default json parser is Jackson.
Jackson many advantages:
-
Jackson rely less jar package, easy to use.
-
Compared with other Java framework Gson json, etc., Jackson json parsing large files faster.
-
Jackson runtime memory footprint is relatively low, the performance is better
-
Jackson has a flexible API, it can easily be extended and customized.
The latest version is 2.9.4, Jackson core module consists of three parts:
-
jackson-core core package, provide API based on the "stream mode" parsing, and including JsonPaser JsonGenerator. Jackson is achieved by a high-performance internal flow pattern of the API and JsonParser JsonGenerator to generate and parse json.
-
jackson-annotations annotation package that provides standard annotations;
-
jackson-databind data bundle to provide on "Object Binding" parsing relevant API (ObjectMapper) and "tree model" Analysis Related API (JsonNode); based on "Object Binding" API and parse "tree model" Analysis based on the analysis of the dependency API API "flow pattern."
Why Jackson introduced such a long ah? Because it is also my favorite.
Json-lib
Project Address: http: //json-lib.sourceforge.net/index.html
json-lib beginning is the most widely used analytical tool json, json-lib a bad place really is dependent on many third-party packages for complex type of conversion, for json json-lib converted into bean as well as defects, such as a class list which will set or map of another class, json-lib problem arises from bean to json conversion. json-lib in function and performance of the above can not meet the needs of the Internet now.
Write performance test
Then start writing these four performance test code library.
Add maven dependence
The first is of course dependent on four add maven repository, in fairness, I use them all the latest version:
<!-- 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>
Four library tools
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 class preparation
Here I wrote a simple Person class, while the class attributes FullName Date, List, Map and custom maximum extent simulate real-world scenarios.
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 + "]
");
if (friends != null) {
str.append("Friends:
");
for (Person f : friends) {
str.append(" ").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 serialization benchmark
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JsonSerializeBenchmark {
/**
* 序列化次数参数
*/
@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;
}
}
Explain the above code
ResultExporter.exportResult("JSON序列化性能", results, "count", "秒");
This is the way I have written to fill Echarts map, then export the png image of the performance test report data, I will not put up specific code, refer to my github source.
After the results of the implementation chart:
As can be seen from the above test results, the number of sequences is small when, Gson best performance, when increasing the time to 100000, Gson weaker than Jackson and FASTJSON details, this property is true when FASTJSON cattle, may also regardless of the number or see fewer and more, Jackson has been outstanding performance. And that is simply to Json-lib funny. ^ _ ^
JSON deserialization performance benchmarks
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JsonDeserializeBenchmark {
/**
* 反序列化次数参数
*/
@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() {
}
}
After the results of the implementation chart:
As can be seen from the above test results, deserialization time, Gson, Jackson and FastJson not very different, very good performance, and that Json-lib or to continue funny.
(Finish)