Best Practices For Heavy Computations in Javascript?

前端 未结 3 1781
春和景丽
春和景丽 2021-02-02 00:41

I am working on client side scripts and need to do heavy computations like pushing huge number of objects in an array, it causes JavaScript to stop response and browser hangs gi

3条回答
  •  余生分开走
    2021-02-02 01:17

    Okay, looking at your code, there's a few things you can optimize:

    var s = chartObj.masterChart.series, // #1
        sLength = s.length,              // #2
        chartMin = chartObj.RangeSelectedMinValue,
        chartMax = chartObj.RangeSelectedMaxValue;
    for (var series = 0; series < sLength; series++) {
        var detailData = [],
            data = s[series].data,       // #3
            length = data.length;        // #2
        for(var i = 0; i < length; i++){ // #4
            var point = data[i];
            if (point.x >= chartMin && point.x <= chartMax) {
                detailData.push({
                    x: point.x,
                    y: point.y
                });
            }
    
        }
        chartObj.detailChart.series[series].setData(detailData);
    }
    
    1. You're getting the same "deeper" object inside chartObj multiple times --> Assign it to a temporary variable;
    2. Don't calculate the length for every iteration of the loop. Same principle as #1
    3. Assign s[series].data to a temp var. This provides a direct pointer to the data instead of having to access s[series].data each iteration of the loop. Same principle as #1
    4. jQuery is slow. For a simple loop, use JavaScript instead, especially if you're looping through a massive object.

    I'm not saying this edit will work miracles, but it should reduce the load a bit.

提交回复
热议问题