美文网首页
fastjson/gson/jackson简单性能对比

fastjson/gson/jackson简单性能对比

作者: 李昂的数字之旅 | 来源:发表于2018-08-30 15:17 被阅读0次
条数\ms fastjson gson jackson
10 293 78 356
1,000 223 150 368
10,000 412 261 569
100,000 596 473 599
1,000,000 920 2258 953
10,000,000 7979 11566 4714
性能对比

由测试结果可以看出

  • fastjson性能比较稳定,API简洁
  • gson序列化次数少时,性能较好
  • jackson序列化次数多时,性能较好,还要强制捕获一堆异常
public class FastJsonLearn {
    public static void main(String[] args) {
        String strTemplate = "{\"k2\": %d, \"k1\": \"1111qwertyuiopasdfghjklzxcvbnm\"}";
        int time = 10000000;

        //预加载json字符
        String[] strs = new String[time];
        for (int i = 0; i < time; i++) {
            strs[i] = String.format(strTemplate, i);
        }

        //fastjson
        run(o -> {
            System.out.println("fastjson");
            for (int i = 0; i < o; i++) {
                Demo demo = JSON.parseObject(strs[i], Demo.class);
                JSON.toJSON(demo);
            }
        }, time);

        //gson
        run(o -> {
            System.out.println("gson");
            Gson gson = new Gson();
            for (int i = 0; i < o; i++) {
                Demo demo = gson.fromJson(strs[i], Demo.class);
                gson.toJson(demo);
            }
        }, time);

        //jackson
        run(o -> {
            System.out.println("jackson");
            ObjectMapper mapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
            for (int i = 0; i < o; i++) {
                Demo demo = null;
                try {
                    demo = mapper.readValue(strs[i], Demo.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mapper.writeValueAsString(demo);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }, time);
    }

    static void run(IntConsumer fn, int time) {
        long s = System.currentTimeMillis();
        fn.accept(time);
        System.out.println("use " + (System.currentTimeMillis() - s) + " ms");
    }

    @Setter
    static class Demo {
        private String k1;
        private Integer k2;
    }
}

相关文章

网友评论

      本文标题:fastjson/gson/jackson简单性能对比

      本文链接:https://www.haomeiwen.com/subject/wkxdwftx.html