用javascript优化处理大数据集

时间:2019-06-26 15:04:00

标签: javascript for-loop optimization hashtable large-data

我正在发送一个get请求,并接收一个带有约50000个元素的数组的JSON对象。我需要遍历50000个数组元素并将所有具有相同用户名的元素组合在一起,然后将该数据添加到代码中的另一个数组中,以便可以在UI网格中显示。

我的第一个解决方案是遍历接收到的50000个元素,并检查它们是否在ui-grid数组中,这需要我遍历ui-grid数组,因此对于来自GET请求的数组中的每个元素遍历ui-grid数组。如果我在ui-grid数组中找到了一个具有相同用户名的元素,那么我只是将整数值加在一起,即

(uiGridArray [i] .views + = GetRequestArray [j] .views)。

我第二次尝试使用键值数组。用户名是关键值。我创建了一个临时数组来存储它们。我将像以前一样循环遍历GET请求数组,而不是循环遍历ui-grid数组以检查用户名,我将首先检查是否存在值tempArray [GetRequestArray [i] .username]的元素(如果不存在),我将创建一个如果确实存在,我将使用键值即

直接转到该元素

(tempArray [GetRequestArray [i] .username] .views + = GetRequestArray [i] .views)

最后,我将遍历tempArray一次,并将其添加到ui-grid数组中。

GetRequestArray-> tempKeyNameArray-> uiGridArray

callAPI.get(options).then(function(value) {
          let dataLength = uiGrid.data.length;

          // formates data from the graylog query into an object and stores the formated
          // objects in a hash table to increase performace while formating the data
          for (let i = 0; i < value.length; i++) {
              $scope.addMessageToHashTableArray(value[i]);
          }

          // add clinical hash table to ui-grid data array
          for (let key in $scope.tempArray) {
            uiGrid.data.push($scope.tempArray[key]);
          }
      })


$scope.addMessageToHashTableArray = function(value) {

      let row = angular.copy($scope.templateRow);
      row.username = value.message.username;
      row.email = value.message.email;
      row.group = $scope.getGroupName(value.message);

      let key = row.username;

      // if a row already exists with the current username and group
      // then update that row with the current values
      if ($scope.tempArray.hasOwnProperty(key)) {
        $scope.tempArray[key].data_view += row.data_view;
        $scope.tempArray[key].records += row.records;
        $scope.tempArray[key].crosstabs += row.crosstabs;
        $scope.tempArray[key].explorer += row.explorer;
        $scope.tempArray[key].bookmarks += row.bookmarks;
        $scope.tempArray[key].reports += row.reports;
        $scope.tempArray[key].total_views += row.total_views;

      }
      // if the row does not exist then create one
      else {
        $scope.tempArray[key] = angular.copy(row);
      }
  }

根据我的测试,密钥对值数组似乎快了4秒,但过程仍然需要30-40秒。有办法优化吗?我希望该过程花费10秒,即将加载时间减少20-30秒

0 个答案:

没有答案
相关问题