fastjson/gson/jackson简单性能对比

2018-08-30  本文已影响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
性能对比

由测试结果可以看出

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;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读