![](/img/trans.png)
[英]Performance differences between controller functions defined on `$scope` or `this` - AngulrJS
[英]Differences between functions and objects, and how it affects performance
任何人都可以解釋為什么下面顯示的兩個例子之間的內存占用似乎有如此大的差異? 我正在使用node.js作為環境。
它們都產生相同的結果和映射
var util = require('util');
var startMem = process.memoryUsage().heapUsed;
/*
var test = function() {
var testvar = function() {
this.innerTest1 = function() {
this.someVal1 = "this is a test";
this.someFunc1 = function() {
return "this is another test";
}
}
this.innerTest2 = function() {
this.someVal2 = "this is a third test";
this.someFunc2 = function() {
return "this is a forth test";
}
}
}
}
*/
//out:
//mem: 448088
var test = function() {
var testvar = {
innerTest1 : {
someVal1 : "this is a test",
someFunc1 : function() {
return "this is another test"
}
},
innerTest2 : {
someVal2 : "this is a third test",
someFunc2 : function() {
return "this is a forth test"
}
}
}
}
for (var i = 0; i < 50000; i++) {
var testobj = new test();
}
//out:
//mem: 1060040
console.log("mem: " + (process.memoryUsage().heapUsed - startMem));
這兩段代碼具有完全不同的行為。
在第一個示例中,在調用包含函數之前, 不會設置或創建屬性/函數。 但是, 永遠不會調用包含函數。
例如,給定:
this.innerTest1 = function() {
// the property is NOT SET until this function is run
this.someVal1 = "this is a test";
// this function is NOT CREATED until this function is run
this.someFunc1 = function() {
return "this is another test";
}
}
同樣,同樣適用於賦值給innerTest1
。 因此,第一個示例代碼等同於以下不太有用的代碼。
var testvar = function() {}
(解析可以被認為是一次性費用。)
在后面的示例中,將分配每個屬性,並且每個函數都是作為對象文字評估的一部分創建的。
在第一個示例中,僅在調用其父函數時才會延遲創建函數,但在第二個示例中,所有成員都初始化為對象文字的一部分。
如果您正在嘗試減少內存占用 ,則應該使用原型鏈,這將允許您在多個實例之間共享功能。
基本上,而不是做:
function test() {
var testvar = {
someFn: function () {}
};
}
你可以做:
var base = {
someFn: function () {}
};
function test() {
var testvar = Object.create(base);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.