输出一个对象列表,这个对象有许多字段及关联字段要序列化为 json,关联对象都使用 eager load 获取出来了。使用 active model serializers 作为序列化器,然后发现序列化好慢,这是 rails server 的 log:
20 个对象:
[active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (297.45ms)
Completed 200 OK in 395ms (Views: 357.6ms | ActiveRecord: 15.6ms)
10 个对象:
[active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (176.06ms)
Completed 200 OK in 240ms (Views: 226.6ms | ActiveRecord: 8.6ms)
5 个对象:
[active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (60.54ms)
Completed 200 OK in 100ms (Views: 89.4ms | ActiveRecord: 7.6ms)
我在代码中直接序列化并计算时间如下:
某次数据库 SQL 的加载情况:
另外发现上面的时间是本地的机器,线上用的是青云性能主机,序列化耗时会增加 100 多 ms。