美文网首页
Fastjson 第一次解析耗时更长

Fastjson 第一次解析耗时更长

作者: new_xd | 来源:发表于2018-05-17 14:52 被阅读0次

    问题

    发现程序开机启动慢,仔细调查,意外发现了fastjson解析慢的问题

    使用fastjson版本

    compile 'com.alibaba:fastjson:1.2.32'
    

    示例说明

        // 在一个单元测试的case里 写代码验证
        @Test
        public void addition_isCorrect() throws Exception {
            assertEquals(4, 2 + 2);
    
            test("空字符串", new Runnable() {
                @Override
                public void run() {
                    List<String> strs = JSON.parseArray("", String.class);
                }
            });
    
            test("[]", new Runnable() {
                @Override
                public void run() {
                    List<String> strs = JSON.parseArray("[]", String.class);
                }
            });
            test("[\"a\"]", new Runnable() {
                @Override
                public void run() {
                    List<String> strs = JSON.parseArray("[\"a\"]", String.class);
                }
            });
        }
    
        public void test(String name, Runnable runnable) {
            long time = System.currentTimeMillis();
            runnable.run();
            System.out.println(name + " cost " + (System.currentTimeMillis() - time) + "\n");
        }
    

    输出结果如下

    空字符串 cost 92
    
    [] cost 0
    
    ["a"] cost 0
    

    简直不敢相信空字符串竟然耗时92ms

    尝试修改了代码和顺序结果如下

    {"a":"hello","b":2} cost 107
    
    ["a"] cost 0
    
    ["a"] again cost 0
    
    [] cost 0
    
    空字符串 cost 0
    

    再修改顺序

    ["a"] cost 103
    
    ["a"] again cost 0
    
    {"a":"hello","b":2} cost 16
    
    [] cost 0
    
    空字符串 cost 0
    
    [] cost 79
    
    ["a"] cost 0
    
    ["a"] again cost 0
    
    {"a":"hello","b":2} cost 10
    
    空字符串 cost 0
    

    发现原来第一次解析比较耗时

    相关文章

      网友评论

          本文标题:Fastjson 第一次解析耗时更长

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