javascript - 如何优化包含对象数组的两个对象的合并

标签 javascript node.js

我需要在将被大量使用的代码路径中合并两个对象。该代码有效,但我担心它没有针对速度进行足够的优化,我正在寻找任何建议来改进/替换我提出的建议。我最初是在本期末尾开始编写示例的:How can I merge properties of two JavaScript objects dynamically? .该解决方案适用于简单的对象。但是,我的需求有所不同,这就是性能问题的来源。我需要能够支持这样的数组

  1. 一个简单值数组将在新对象中查找值并将这些值添加到现有对象的末尾
  2. 对象数组将合并对象(基于 id 属性的存在)或将新对象(id 属性不存在的对象)推到现有数组的末尾。

我不需要函数/方法克隆,我也不关心 hasOwnProperty,因为对象在合并后返回到 JSON 字符串。

任何帮助我从中获得最后一次性能的建议将不胜感激。

var utils = require("util");

function mergeObjs(def, obj) {
  if (typeof obj == 'undefined') {
    return def;
  } else if (typeof def == 'undefined') {
    return obj;
  }

  for (var i in obj) {
    // if its an object
    if (obj[i] != null && obj[i].constructor == Object)
    {
      def[i] = mergeObjs(def[i], obj[i]);
    }
    // if its an array, simple values need to be joined.  Object values need to be remerged.
    else if(obj[i] != null && utils.isArray(obj[i]) && obj[i].length > 0)
    {
      // test to see if the first element is an object or not so we know the type of array we're dealing with.
      if(obj[i][0].constructor == Object)
      {
        var newobjs = [];
        // create an index of all the existing object IDs for quick access.  There is no way to know how many items will be in the arrays.
        var objids = {}
        for(var x= 0, l= def[i].length ; x < l; x++ )
        {
          objids[def[i][x].id] = x;
        }

        // now walk through the objects in the new array
        // if the ID exists, then merge the objects.
        // if the ID does not exist, push to the end of the def array
        for(var x= 0, l= obj[i].length; x < l; x++)
        {
          var newobj = obj[i][x];
          if(objids[newobj.id] !== undefined)
          {
            def[i][x] = mergeObjs(def[i][x],newobj);
          }
          else {
            newobjs.push(newobj);
          }
        }

        for(var x= 0, l = newobjs.length; x<l; x++) {
          def[i].push(newobjs[x]);
        }
      }
      else {
        for(var x=0; x < obj[i].length; x++)
        {
          var idxObj = obj[i][x];
          if(def[i].indexOf(idxObj) === -1) {
             def[i].push(idxObj);
          }
        }
      }
    }
    else
    {
      def[i] = obj[i];
    }
  }
  return def;}

要合并的对象样本:

var obj1 = {
            "name" : "myname",
            "status" : 0,
            "profile": { "sex":"m", "isactive" : true},
            "strarr":["one", "three"],
            "objarray": [
                {
                    "id": 1,
                    "email": "a1@me.com",
                    "isactive":true
                },
                {
                    "id": 2,
                    "email": "a2@me.com",
                    "isactive":false
                }
            ]
        };
        var obj2 = {
            "name" : "myname",
            "status" : 1,
            "newfield": 1,
            "profile": { "isactive" : false,  "city": "new York"},
            "strarr":["two"],
            "objarray": [
                {
                    "id": 1,
                    "isactive":false
                },
                {
                    "id": 2,
                    "email": "a2modified@me.com"
                },
                {
                    "id": 3,
                    "email": "a3new@me.com",
                    "isactive" : true
                }
            ]
        };

一旦合并,这个 console.log(mergeObjs(obj1, obj2)) 应该产生这个:

{ name: 'myname',
  status: 1,
  profile: { sex: 'm', isactive: false, city: 'new York' },
  strarr: [ 'one', 'three', 'two' ],
  objarray: 
   [ { id: 1, email: 'a1@me.com', isactive: false },
     { id: 2, email: 'a2modified@me.com', isactive: false },
     { id: 3, email: 'a3new@me.com', isactive: true } ],
  newfield: 1 }

最佳答案

我会查看:https://github.com/bestiejs/lodash

_.merge 不在“优化”函数列表中,但这是经过实战考验、久经沙场的。他还有一个性能套件,可能会询问您如何为性能套件做出贡献,以便对 merge 实现有一些了解。

https://github.com/bestiejs/lodash/blob/master/lodash.js#L1677-1738

编辑:顺便说一句,我不会过早地优化。我会看看这在您的用例中是否真的是一个问题,然后继续处理实际数据。我会看类似的东西:https://github.com/felixge/faster-than-c

基本原则:

  • 收集数据
  • 分析一下
  • 发现问题
  • 修复它们
  • 重复

他对每一个都有提示。

关于javascript - 如何优化包含对象数组的两个对象的合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771077/

相关文章:

javascript - 通过使用 Javascript 反转 URL 来隐藏机器人的 URL

Javascript将字符串数组的数组转换为数字数组的数组

javascript - if 语句中的 jQuery/javascript 变量不起作用

javascript - 如何使用 Mocha 配置 TeamCity 构建?

javascript - 当 require ("http").Server() 以 Express 应用程序作为参数进行评估时发生了什么?

javascript - 我为我的网站添加了一个 Lightbox jquery,但我想删除每次出现的蓝色边框

node.js - node.js 是否保留异步执行顺序?

node.js - 使用 beforeCreate 钩子(Hook)继续创建模型

javascript - server.listen() 实际上做了什么?

javascript - 这个 JavaScript 如何在 Firefox 中打开 Windows 设置?