JS性能优化-fast-json-stringify

最近看到一个新的插件,做下记录。
常规的 JSON 字符串转换如下:

const obj = { id: 1, name: ‘name’ };
const jsonStr = JSON.stringify(obj); // 转换为字符串
const json = JSON.parse(jsonStr); // 转换为对象

平时我们都是用 JSON.stringify 来将对象转换为JSON字符串,可是如果是对于有固定属性的转换对象来说,fast-json-stringify 可以提高转换的性能。下面来说一下用法。

const fastJson = require('fast-json-stringify');
const stringify = fastJson({
  title: 'example',
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'integer' }
  }
});
console.log(stringify({ name: 'name', age: 1 }));  
//  {"name":"name","age":1}

性能方面也是优于JSON.stringify的
在这里插入图片描述
在github上有很多属性,可以适用于很多复杂场景,也有详细的介绍。
https://github.com/fastify/fast-json-stringify

猜你喜欢

转载自blog.csdn.net/kelly0721/article/details/87258272
今日推荐