我正在寻找实现模块功能的最佳方法,包括内存消耗以及执行时间/步骤。
为了呈现我的方法,我创建了三个例子。
我的建议如下:
1。简单方法
function module(newId) {
//private vars
var settings = {
id: newId,
name: ''
};
//module object including large amount of code
return {
getId: function() {
return settings.id;
},
getName: function() {
return settings.name;
},
setName: function(newName) {
//[...] large amount of code [...]
settings.name = newName;
}
};
}
2。模块中的子功能
function module(newId) {
//private vars
var settings = {
id: newId,
name: ''
};
//put large amount of code here too keep it outside returned object
function getIdFunc() {
return settings.id;
}
function getNameFunc() {
return settings.name;
}
function setNameFunc(newName) {
//[...] large amount of code [...]
settings.name = newName;
}
//returned module object: looks smaller - does it consume less memory?
return {
getId: getIdFunc,
getName: getNameFunc,
setName: setNameFunc
};
}
第3。模块外的子功能
//put large amount of code here too keep it outside module function
var moduleFunc = {
getId: function(settings) {
return settings.id;
},
getName: function(settings) {
return settings.name;
},
setName: function(settings) {
//[...] large amount of code [...]
settings.name = newName;
}
};
function module(newId) {
var settings = {
id: newId,
name: ''
};
//returned module object: should be very small in memory
// - but what about performance?
return {
getId: function() {
moduleFunc.getId(settings);
},
getName: function() {
moduleFunc.getName(settings);
},
setName: function() {
moduleFunc.setName(settings);
}
};
}
假设创建了大量模块并将其存储在内存中,如下所示:
//will myModules be small in memory?
var myModules = [];
for (var i = 0; i < 10000; i++) {
myModules.push(module('test'+i));
//does the call to setName perform well?
myModules[myModules.length-1].setName('just a test');
}
请告诉我关于性能的创建模式,并尝试在枚举专家和骗局时区分内存消耗和执行时间/步骤。
答案 0 :(得分:0)