前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >js传递json数据过大的解决方案

js传递json数据过大的解决方案

作者头像
sofu456
发布于 2023-12-18 05:03:08
发布于 2023-12-18 05:03:08
35200
代码可运行
举报
文章被收录于专栏:sofu456sofu456
运行总次数:0
代码可运行

protobufjs

使用protobuf,定义如下结构 Person.protobuf

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
}

Person.thrift

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
namespace java com.example.Person

struct Person {
  1: required string name,
  2: required i32 age
}

使用benchmark基线代码测试如下

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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支持不太好就没有写测试例子了。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-12-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • protobufjs
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档