编程语言
首页 > 编程语言> > javascript-angular.equals和_.isEqual有什么区别?

javascript-angular.equals和_.isEqual有什么区别?

作者:互联网

我的意思是说性能有什么区别吗?哪一个能够进行最好的深度比较?有时,角度的equals函数无法找到所有差异.

我还注意到,该函数的棱角版本没有检查’$$hashKey’键.

解决方法:

通过比较值本身和所有内部属性,它们的行为基本上相同.性能也几乎是相同的,至少对于10000个元素而言,这将在100-200毫秒内有所不同.我已经创建了小型测试套件,警告:运行代码段时,浏览器页面将冻结几秒钟.我不太确定这是衡量性能的正确方法,因此可以随时提出更好的建议.

angular
.module("comparsion", [])
.controller("ComparsionCtrl", function($scope) {
  var testCases = 10000;
  
  console.time("underscore");
  for(var i = 0; i < testCases; i++) {
    var obj = createRandomObj(5, true);
    var obj1 = createRandomObj(5, true);
    _.isEqual(obj, obj1);
  }
  console.timeEnd("underscore");
  
  console.time("angular");
  for(var i = 0; i < testCases; i++) {
    var obj = createRandomObj(5, true);
    var obj1 = createRandomObj(5, true);
    angular.equals(obj, obj1);
  }
  console.timeEnd("angular");
  
  // Random object generator from https://stackoverflow.com/questions/2443901/random-object-generator-in-javascript
  function createRandomObj(fieldCount, allowNested)
{
    var generatedObj = {};

    for(var i = 0; i < fieldCount; i++) {
        var generatedObjField;

        switch(randomInt(allowNested ? 6 : 5)) {

            case 0:
            generatedObjField = randomInt(1000);
            break;

            case 1:
            generatedObjField = Math.random();
            break;

            case 2:
            generatedObjField = Math.random() < 0.5 ? true : false;
            break;

            case 3:
            generatedObjField = randomString(randomInt(4) + 4);
            break;

            case 4:
            generatedObjField = null;
            break;

            case 5:
            generatedObjField = createRandomObj(fieldCount, allowNested);
            break;
        }
        generatedObj[randomString(8)] = generatedObjField;
    }
    return generatedObj;
}

// helper functions

function randomInt(rightBound)
{
    return Math.floor(Math.random() * rightBound);
}

function randomString(size)
{
    var alphaChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var generatedString = '';
    for(var i = 0; i < size; i++) {
        generatedString += alphaChars[randomInt(alphaChars.length)];
    }

    return generatedString;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<div ng-app="comparsion">
  <div ng-controller="ComparsionCtrl"></div>
</div>

标签:performance,angularjs,underscore-js,javascript
来源: https://codeday.me/bug/20191118/2026569.html