首页 > 代码库 > js创建对象的四种方式以及消耗时间比较

js创建对象的四种方式以及消耗时间比较

// Property-less object console.time(‘zoop1‘);var zoop = (function (numObjects) {  var pooz = Object.create(null);  for(var i = 0; i< numObjects; i++) {    pooz[i] = Object.create(null);  }  return pooz;})(1000000);console.timeEnd(‘zoop1‘); // Using Object Literalconsole.time(‘zoop2‘);var zoop = (function (numObjects) {  var pooz = {};  for(var i = 0; i< numObjects; i++) {    pooz[i] = {};  }  return pooz;})(1000000);console.timeEnd(‘zoop2‘); // Object.create({})console.time(‘zoop3‘);var zoop = (function (numObjects) {  var pooz = Object.create({});  for(var i = 0; i< numObjects; i++) {    pooz[i] = Object.create({});  }  return pooz;})(1000000);console.timeEnd(‘zoop3‘); // new Objectconsole.time(‘zoop4‘);var zoop = (function (numObjects) {  var pooz = new Object();  for(var i = 0; i< numObjects; i++) {    pooz[i] = new Object();  }  return pooz;})(1000000);console.timeEnd(‘zoop4‘);
来源:https://gist.github.com/shubhadeep/371f9245656d5937af09

消耗的时间从少到多>>: 2时间总是最少的,其他三个有变动,一般3消耗时间最多。