示例工程 ch12-json
ch12-json/lib/src/perf.dart
/// 大 JSON 的编解码成本,以及为什么要考虑 isolate。
///
/// `jsonDecode` 是纯 CPU 的同步调用:20k 行数据通常几十毫秒,
/// 在 Flutter 里就是掉好几帧。>16ms 就该考虑丢进 isolate(ch08)。
library;
import 'dart:convert';
import 'dart:isolate';
/// 造一个"够大"的 JSON 字符串(rows 条记录)。
String buildFixture(int rows) => jsonEncode(<String, Object?>{
'version': 1,
'rows': <Map<String, Object?>>[
for (var i = 0; i < rows; i++)
<String, Object?>{
'id': i,
'name': 'item-$i',
'price_cents': i * 3,
'active': i.isEven,
'tags': <String>['a', 'b', 'tag-$i'],
},
],
});
/// 解码并统计记录数(纯函数,便于单测与 isolate 复用)。
int countRows(String raw) {
final Object? decoded = jsonDecode(raw);
if (decoded is! Map<String, Object?>) {
throw const FormatException('期望顶层是 object');
}
final Object? rows = decoded['rows'];
if (rows is! List<Object?>) {
throw const FormatException('rows 应该是数组');
}
return rows.length;
}
/// 在后台 isolate 里解码:UI isolate 不卡。
Future<int> countRowsInIsolate(String raw) => Isolate.run<int>(() => countRows(raw));
/// 把解码后的对象重新编码,测"编码"的成本。
String reEncode(String raw) => jsonEncode(jsonDecode(raw));