JavaScript匿名函数内存分配和垃圾分配
JavaScript anonymous function memory allocation and garbage allocation
// This is a Framework Method
function ajaxJSONType(uri, reqtype , reqJSON , callback){
var url : uri;
$jq.ajax({
url: uri,
type: reqtype,
data:reqJSON ,
dataType: ResponseDataType.JSON,
sucess: function(data){
// do some validation on response data and call the callback function
callback(data);
},
});
}
每个开发人员都从他们的代码中调用这个方法,就像这样
第一种方法:
function MyMethod(){
var reqdata = {};
ajaxJSONType(serviceUri , ReqType.POST,function(responsedata){
// Here some processing on the response will occur
});
}
这里的回调方法是一个匿名函数,用于解析响应和处理。
第二种方法:
function MyMethod(){
var reqdata = {};
ajaxJSONType(serviceUri , ReqType.POST,myCallbackFun);
}
function myCallbackFun(responsedata){
// Here some processing on the response will occur
}
我的问题:
如果 MyMethod 在短时间内被调用超过 1000 次..
Will it good to have the anonymous function or named function ?
The First approch will create function object 1000 times ?
I saw in JSLINT , we should not create anonymous function inside a loop.
here though we dont have any loop the MyMethod will be called many times by other events. So it is also like a Loop.
我使用的是IE 9浏览器。
I saw in JSLINT , we should not create anonymous function inside a loop.
JSLint中的reason for the warning是对函数在循环内创建的闭包的潜在误解。与性能无关。
Will it good to have the anonymous function or named function ?
正如您所提到的,通过将函数表达式直接传递到调用中,引擎必须在您每次调用 MyMethod
时创建该函数的新副本。出于这个原因,在这种情况下最好使用函数声明。但是,不要陷入过早的优化中……您不太可能注意到任何真正的性能提升。
// This is a Framework Method
function ajaxJSONType(uri, reqtype , reqJSON , callback){
var url : uri;
$jq.ajax({
url: uri,
type: reqtype,
data:reqJSON ,
dataType: ResponseDataType.JSON,
sucess: function(data){
// do some validation on response data and call the callback function
callback(data);
},
});
}
每个开发人员都从他们的代码中调用这个方法,就像这样
第一种方法:
function MyMethod(){
var reqdata = {};
ajaxJSONType(serviceUri , ReqType.POST,function(responsedata){
// Here some processing on the response will occur
});
}
这里的回调方法是一个匿名函数,用于解析响应和处理。
第二种方法:
function MyMethod(){
var reqdata = {};
ajaxJSONType(serviceUri , ReqType.POST,myCallbackFun);
}
function myCallbackFun(responsedata){
// Here some processing on the response will occur
}
我的问题:
如果 MyMethod 在短时间内被调用超过 1000 次..
Will it good to have the anonymous function or named function ?
The First approch will create function object 1000 times ?
I saw in JSLINT , we should not create anonymous function inside a loop.
here though we dont have any loop the MyMethod will be called many times by other events. So it is also like a Loop.
我使用的是IE 9浏览器。
I saw in JSLINT , we should not create anonymous function inside a loop.
JSLint中的reason for the warning是对函数在循环内创建的闭包的潜在误解。与性能无关。
Will it good to have the anonymous function or named function ?
正如您所提到的,通过将函数表达式直接传递到调用中,引擎必须在您每次调用 MyMethod
时创建该函数的新副本。出于这个原因,在这种情况下最好使用函数声明。但是,不要陷入过早的优化中……您不太可能注意到任何真正的性能提升。