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])])})
  .add('lz4', ()=>{ lz4_result = lz4.encode(json_result)})  //测试序列化和lz4压缩效率
  .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])})
  .add('lz4-de', ()=>{ lz4.decode(lz4_result)})
  .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支持不太好就没有写测试例子了。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐