protobufjs
使用protobuf,定义如下结构
Person.protobuf
syntax = "proto3";
message Person {
string name = 1;
int32 age = 2;
}
Person.thrift
namespace java com.example.Person
struct Person {
1: required string name,
2: required i32 age
}
使用benchmark基线代码测试如下
const fs = require('fs');
const path = require('path');
const BSON = require('bson')
const msgpack = require('msgpack-lite');
const Benchmark = require('benchmark');
const thriftrw = require('thriftrw')
const protobuf = require('protobufjs');
const protobufPerson = protobuf.loadSync('Person.proto');
const Person = protobufPerson.lookupType('Person');
var thrift = new thriftrw.Thrift({
source: fs.readFileSync(path.join(__dirname, 'Person.thrift'), 'utf8'),
allowOptionalArguments: true,
});
const jsonData = {name: "John", age: 30};
let json_result,bson_result,msgpack_result,proto_result,thrift_result,dimbin_result;
console.log('----------serialize----------')
new Benchmark.Suite()
.add('JSON', ()=>{ json_result = JSON.stringify(jsonData)})
.add('BSON', ()=>{ bson_result = BSON.serialize(jsonData)})
.add('msgpack', ()=>{ msgpack_result = msgpack.encode(jsonData)})
.add('protobuf', ()=>{ proto_result = Person.encode(jsonData).finish()})
.add('thrift', ()=>{ thrift_result = thrift.Person.toBuffer(jsonData)})
.add('dimbin', ()=>{ dimbin_result = dimbin.serialize([dimbin.stringsSerialize(jsonData.name),new Uint32Array([30])])})
.on('cycle', (event) => console.log(String(event.target)))
.on('complete', function() {console.log('Fastest is ' + this.filter('fastest').map('name'))})
.run()
console.log('----------deserialize----------')
new Benchmark.Suite()
.add('JSON—de', ()=>{ JSON.parse(json_result)})
.add('BSON-de', ()=>{ BSON.deserialize(bson_result)})
.add('msgpack-de', ()=>{ msgpack.decode(msgpack_result)})
.add('protobuf-de', ()=>{ Person.decode(proto_result)})
.add('thrift-de', ()=>{ thrift.Person.fromBuffer(thrift_result)})
.add('dimbin-de', ()=>{ o=dimbin.parse(dimbin_result);dimbin.stringsParse(o[0])})
.on('cycle', (event) => console.log(String(event.target)))
.on('complete', function() {console.log('Fastest is ' + this.filter('fastest').map('name'))})
.run()
执行结果如下:
小文件json数据解析,probuf比msgpack、thrift的快一个数量级
10m左右的json数据解析,probuf比json快一个数量级,msgpack、thrift和probuf差别不大
还有一些其他的框架,如fastcdr和flatbuffer,js支持不太好就没有写测试例子了。