我有一个 Ballerina 程序,我使用自定义
convertToJson
函数将记录流转换为 JSON。当前的实现涉及循环遍历每条记录并调用toJson
方法,导致明显的性能瓶颈和较高的内存消耗。
import ballerina/io;
public function main() returns error? {
stream<ScanRecord> scanRecords = getScanRecordStream(); // large stream
json[] jsonData = convertToJson(scanRecords);
io:println(jsonData);
}
type ScanRecord record {
int id;
string name;
};
function convertToJson(stream<ScanRecord> scanRecords) returns json[] {
json[] output = [];
scanRecords.forEach(function(ScanRecord scanRecord) {
output.push(scanRecord.toJson());
});
return output;
}
当前的方法执行大约需要 4 秒,我正在寻找一种更有效的方法来直接将流转换为 JSON,而无需迭代每个记录。 Ballerina 是否有任何功能或优化可以帮助提高此操作的性能和内存效率?
如果
ScanRecord
仅包含与 JSON 兼容的字段,则可以通过将其设为 json
的子类型来优化转换过程。
这里有两种方法:
type ScanRecord record {|
int id;
string name;
|};
ScanRecord
设为开放记录,允许额外字段,但将其余描述符显式指定为 json
。这确保任何其他字段也属于 json。type ScanRecord record {|
int id;
string name;
json...;
|};
通过这些方法,
ScanRecord
成为json
的子类型,可以在需要json值的地方直接使用,而无需使用toJson()
进行转换。
示例
function convertToJson(stream<ScanRecord> scanRecords) returns json[] {
return from ScanRecord rec in scanRecords select rec;
}