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