GSON解性能瓶颈分析

    GSON是Google提供的开源库,使用很便捷,但是在使用过程中也发现了其短板,在Bean类结构复杂时,进行反序列化耗时占比较高,尤其是很多在应用启动阶段需要反序列化一些内置的数据时,很让人头疼,通过抓Trace能发现这个耗时占比较高。

gson反序列化过程火焰图
GSON解性能瓶颈分析_第1张图片

GSON解性能瓶颈分析_第2张图片
json结构:

{
  "name":"zhang",
  "age":33,
  "sex":1,
  "bestStudent":{
    "name":"san",
    "age":10,
    "sex":1,
    "grade":1,
    "favoriteSubject":{
      "subjectName":"music",
      "subjectScore":90.1
    },
    "subjects":[
      {
        "subjectName":"music",
        "subjectScore":90.1
      },
      {
        "subjectName":"literature",
        "subjectScore":80.1
      },
      {
        "subjectName":"mathematics",
        "subjectScore":70.1
      }
    ]
  },
  "students":[
    {
      "name":"li",
      "age":10,
      "sex":1,
      "grade":1,
      "favoriteSubject":{
        "subjectName":"music",
        "subjectScore":90.1
      },
      "subjects":[
        {
          "subjectName":"music",
          "subjectScore":90.1
        },
        {
          "subjectName":"literature",
          "subjectScore":80.1
        },
        {
          "subjectName":"mathematics",
          "subjectScore":70.1
        }
      ]
    },
    {
      "name":"wang",
      "age":10,
      "sex":1,
      "grade":1,
      "favoriteSubject":{
        "subjectName":"literature",
        "subjectScore":80.1
      },
      "subjects":[
        {
          "subjectName":"music",
          "subjectScore":90.1
        },
        {
          "subjectName":"literature",
          "subjectScore":80.1
        },
        {
          "subjectName":"mathematics",
          "subjectScore":70.1
        }
      ]
    },
    {
      "name":"zhou",
      "age":10,
      "sex":1,
      "grade":1,
      "favoriteSubject":{
        "subjectName":"music",
        "subjectScore":90.1
      },
      "subjects":[
        {
          "subjectName":"music",
          "subjectScore":90.1
        },
        {
          "subjectName":"literature",
          "subjectScore":80.1
        },
        {
          "subjectName":"mathematics",
          "subjectScore":70.1
        }
      ]
    }
  ]

}

    为了从正面优化这个问题,于是我翻看了GSON反序列化的源码,实现了能优化的方案,希望能帮助到同样面临该问题的同学们,如有问题也可以提出来。
如上图GSON解析过程的耗时可以看出在反序列化过程中使用了大量反射调用导致性能问题。

参考文章

【1】抖音 Android 性能优化系列:启动优化实践

你可能感兴趣的:(Android开源框架,开发经验总结,android,开发语言,性能优化)