串化/解析的优化

问题描述

我有一个网络工作者在做一些昂贵的屏幕外计算。它将以大约20ms的增量将数据发送回主线程以进行动画处理。

工作程序结果包含在一个对象数组中,该对象数组最多可以包含2000行。为了将其传递回主线程,我使用了stringify(在Web worker端)和parse(在主线程中)。目前,该过程在两端都很缓慢。

由于动画中并非所有对象中包含的数据都是必需的,因此我尝试编写替换函数以减少发送的数据量(截断一些长浮点并完全忽略某些字段)。但是,这使情况变得更糟。

下面是对stringify / parse过程的定时模拟,以及我未能改进它的尝试。

任何有关如何改善此问题的建议将不胜感激。

let myArray = [];

//Add 2000 'things'

for (let i = 0; i < 2000; i++) {
    let newObject = {};
    newObject.ID = i;
    newObject.percent = 100;
    newObject.nestedArray = [1,2,3,4,5];
    newObject.X = 78940;
    newObject.Y = 893402;
    newObject.detailedFloat1 = Math.random() * Math.random();
    newObject.detailedFloat2 = Math.random() * Math.random();
    newObject.detailedFloat3 = Math.random() * Math.random();
    newObject.detailedFloat4 = Math.random() * Math.random();
    newObject.text = "this is some text";
    newObject.text2 = "this is some more text";
    newObject.foreignKey = 12356;
    myArray.push(newObject);
}

//start a timer
let myTimer = new Date();

//stringify it 
let arrayAsString = JSON.stringify(myArray);
let t1Result = new Date() - myTimer;
timer = new Date();

//parse it
let mySecondArray = JSON.parse(arrayAsString);
let t2Result = new Date() - myTimer;

console.log("un-optimised results");
console.log(t1Result + "ms to stringify");
console.log(t2Result + "ms to parse");
console.log(t2Result + t1Result + "ms total");
console.log("-----");

//optimisation attempt 1 - use a replacor
function replacer(key,value) {
    // Filtering out properties
    if (key == "text" || key == "text2" || key == "foreignKey") {
        return undefined;
    } else if (typeof (value) == "float" || typeof (value) == "number") {
        return Math.round(value * 10000) / 10000;
    } else {
        return value;
    }
}


//start a timer
myTimer = new Date();

//stringify it 
arrayAsString = JSON.stringify(myArray,replacer);
t1Result = new Date() - myTimer;
timer = new Date();

//parse it
mySecondArray = JSON.parse(arrayAsString);
t2Result = new Date() - myTimer;

console.log("replacer results");
console.log(t1Result + "ms to stringify");
console.log(t2Result + "ms to parse");
console.log(t2Result + t1Result + "ms total"); //this has actually made performance worse

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...