首先声明这个测试不是严谨的基准测试( Benchmark Testing),只是自己用来说明一些问题的代码,
比如严谨的测试应该是测试多次并列举出内存占用,cpu使用情况,执行的最大时间、最小时间平均时间等等等。
废话不多说先上代码
首先是Book的实体类,尽量将一些常用类型包括
package com.example.demo.model;
import java.time.LocalDateTime;
import java.util.List;
public class Book {
private Long id;
private Integer no;
private String name;
private Double price;
private String[] authors;
private List<String> authorList;
private LocalDateTime publishTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String[] getAuthors() {
return authors;
}
public void setAuthors(String[] authors) {
this.authors = authors;
}
public List<String> getAuthorList() {
return authorList;
}
public void setAuthorList(List<String> authorList) {
this.authorList = authorList;
}
public LocalDateTime getPublishTime() {
return publishTime;
}
public void setPublishTime(LocalDateTime publishTime) {
this.publishTime = publishTime;
}
}
其中对GC等的一些处理不是很合理,而且只是针对一种序列化的情况,所以这个针对两个JSON库的对比是非常肤浅的。
不过代码基本消除缓存和JIT的影响,所以不会对最后的认知造成大的误差
package com.example.demo;
import static com.example.demo.util.LocalDateTimeUtils.DATE_FORMATTER;
import static com.example.demo.util.LocalDateTimeUtils.DATE_TIME_FORMATTER;
import static com.example.demo.util.LocalDateTimeUtils.TIME_FORMATTER;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.demo.model.Book;
import com.example.demo.util.LocalDateTimeUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class JsonToolSpeedCompare {
private final Logger logger = LoggerFactory.getLogger(getClass());
private ObjectMapper mapper;
private Gson gson;
private Book book;
public void initJacksonMapper() {
mapper = new ObjectMapper();
// 忽略空属性
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);//格式化
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
JavaTimeModule timeModule = new JavaTimeModule();
timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DATE_FORMATTER));
timeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(TIME_FORMATTER));
timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME_FORMATTER));
timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DATE_FORMATTER));
timeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(TIME_FORMATTER));
mapper.registerModule(timeModule);
}
public void initGson() {
gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.format(LocalDateTimeUtils.DATE_TIME_FORMATTER));
}
}).registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String dateTimeStr = json.getAsJsonPrimitive().getAsString();
return LocalDateTime.parse(dateTimeStr, LocalDateTimeUtils.DATE_TIME_FORMATTER);
}
}).create();
}
public void initBook() {
String[] authors = new String[] { "alan turing", "ken thompson", "dennis richard" };
List<String> authorList = Arrays.asList("alan turing", "ken thompson", "dennis richard");
book = new Book();
book.setId(1000L);
book.setNo(2000);
book.setAuthors(authors);
book.setAuthorList(authorList);
book.setName("the orgin of computer technology");
book.setPrice(100.0);
book.setPublishTime(LocalDateTimeUtils.MIN);
}
@Before
public void init() {
initJacksonMapper();
initGson();
initBook();
}
@Test
public void test1() throws JsonProcessingException, InterruptedException {
logger.error("jackson write string:{}", mapper.writeValueAsString(book));
logger.error("gson tojson string:{}", gson.toJson(book));
logger.error("help JIT,so loop write jackson and gson 10000 times");
for (int i = 0; i < 10000; i++) {
mapper.writeValueAsString(book);
gson.toJson(book);
}
logger.error("help JIT end");
Thread.sleep(100);
logger.error("next count elasped time");
// 循环1000万次
long maxCount = 1000_0000L;
logger.error("start jackson test");
long startMillis = System.currentTimeMillis();
for (long l = 0; l < maxCount; l++) {
mapper.writeValueAsString(book);
}
long endMillis = System.currentTimeMillis();
logger.error("end jackson test");
logger.error("jackson eval {} times: {}millis seconds", maxCount, endMillis - startMillis);
logger.info("------------神秘分割线------------");
System.gc();
// help gc
Thread.sleep(1000L);
logger.error("start gson test");
long startMillis1 = System.currentTimeMillis();
for (long l = 0; l < maxCount; l++) {
gson.toJson(book);
}
long endMillis1 = System.currentTimeMillis();
logger.error("end gson test");
logger.error("gson eval {} times: {}millis seconds", maxCount, endMillis1 - startMillis1);
}
}
下面是我的其中一次测试的输出
JRE Azul Systems, Inc./12.0.1 is not supported, advanced source lookup disabled.
10:45:04.204 [main] ERROR com.example.demo.JsonToolSpeedCompare - jackson write string:{"id":1000,"no":2000,"name":"the orgin of computer technology","price":100.0,"authors":["alan turing","ken thompson","dennis richard"],"authorList":["alan turing","ken thompson","dennis richard"],"publishTime":"1970-01-01 00:00:00"}
10:45:04.216 [main] ERROR com.example.demo.JsonToolSpeedCompare - gson tojson string:{"id":1000,"no":2000,"name":"the orgin of computer technology","price":100.0,"authors":["alan turing","ken thompson","dennis richard"],"authorList":["alan turing","ken thompson","dennis richard"],"publishTime":"1970-01-01 00:00:00"}
10:45:04.216 [main] ERROR com.example.demo.JsonToolSpeedCompare - help JIT,so loop write jackson and gson 10000 times
10:45:04.370 [main] ERROR com.example.demo.JsonToolSpeedCompare - help JIT end
10:45:04.471 [main] ERROR com.example.demo.JsonToolSpeedCompare - next count elasped time
10:45:04.471 [main] ERROR com.example.demo.JsonToolSpeedCompare - start jackson test
10:45:13.276 [main] ERROR com.example.demo.JsonToolSpeedCompare - end jackson test
10:45:13.276 [main] ERROR com.example.demo.JsonToolSpeedCompare - jackson eval 10000000 times: 8805millis seconds
10:45:13.276 [main] INFO com.example.demo.JsonToolSpeedCompare - ------------神秘分割线------------
10:45:14.299 [main] ERROR com.example.demo.JsonToolSpeedCompare - start gson test
10:45:42.114 [main] ERROR com.example.demo.JsonToolSpeedCompare - end gson test
10:45:42.114 [main] ERROR com.example.demo.JsonToolSpeedCompare - gson eval 10000000 times: 27815millis seconds