// 对 String s2 = "{\"name\":\"dawang\",\"id\":18}"; 执行 1000000000 反序列化
Test.Person person = Test.Person.newBuilder().setName("dawang").setId(18).build();
byte[] byteArray1 = person.toByteArray();
Test.Person.parseFrom(byteArray1); // 耗时 5s
JSONObject.parse(s) //耗时 17s
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(s2, Persion.class); // 耗时 22s
Gson gson = new Gson();
gson.fromJson(s2, Persion.class); // 耗时 44s
private static void testGson() throws JsonProcessingException {
Gson gson = new Gson();
String s2 = "{\"name\":\"dawang\",\"id\":18}";
// 记录开始时间
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
// 反序列化 Persion
gson.fromJson(s2, Persion.class);// 441
}
// 记录结束时间
long endTime = System.currentTimeMillis();
// 记录耗时,单位 s
System.out.println("耗时:" + (endTime - startTime) / 1000 + "s-testGson");
}
private static void testJSONObject() throws JsonProcessingException {
String s2 = "{\"name\":\"dawang\",\"id\":18}";
// 记录开始时间
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
// 使用fastjson 反序列化
// JSONObject.parse(s2); //160
JSON.parse(s2);
}
// 记录结束时间
long endTime = System.currentTimeMillis();
// 记录耗时,单位 s
System.out.println("耗时:" + (endTime - startTime) / 1000 + "s-testJSONObject");
}
private static void testObjectMapper() throws JsonProcessingException {
String s2 = "{\"name\":\"dawang\",\"id\":18}";
ObjectMapper objectMapper = new ObjectMapper();
// 记录开始时间
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
objectMapper.readValue(s2, Persion.class); //100000000 522s
}
// 记录结束时间
long endTime = System.currentTimeMillis();
// 记录耗时,单位 s
System.out.println("耗时:" + (endTime - startTime) / 1000 + "s-testObjectMapper");
}
private static void testProtobuf() throws InvalidProtocolBufferException {
Test.Person person = Test.Person.newBuilder().setName("dawang").setId(18).build();
byte[] byteArray1 = person.toByteArray();
// 记录开始时间
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
// 反序列化 byteArray1
Test.Person.parseFrom(byteArray1);
}
// 记录结束时间
long endTime = System.currentTimeMillis();
// 记录耗时,单位 s
System.out.println("耗时:" + (endTime - startTime) / 1000 + "s-testProtobuf");
}