this is my code
function function_to_c开发者_如何转开发all(text){
var variable_need = new Array (
0x3131, 0x3132, 0x3134, 0x3137, 0x3138, 0x3139,
0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147,
0x3148, 0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e
);
......
return v;
}
function_to_call(a)
function_to_call(b)
function_to_call(c)
Is variable_need
generated every time when function_to_call
called?
If function_to_call
called frequently...
Is it need to make prototype to prevent memory leak?
Others have answered your questions, but you can also keep a reference to the variable in a closure so it isn't created each time and isn't a global variable, but is available to the function_to_call
function:
var function_to_call = (function() {
var variable_need = [
0x3131, 0x3132, 0x3134, 0x3137, 0x3138, 0x3139,
0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147,
0x3148, 0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e
];
return function (text) {
// variable_need available here
return v;
};
}());
function_to_call(a)
function_to_call(b)
function_to_call(c)
Define your variable_need
array outside your function definition:
var variable_need = [
0x3131, 0x3132, 0x3134, 0x3137, 0x3138, 0x3139,
0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147,
0x3148, 0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e
];
function function_to_call(text) {
// do stuff with variable_need
return v;
}
function_to_call(a);
function_to_call(b);
function_to_call(c);
Is "variable_need" generated every time when "function_to_call" called?
Yes.
It wouldn't be if you defined it outside the function, but then it wouldn't be reset each time (so if the function modified it, then it would remain modified for subsequent calls).
If "function_to_call" called frequently... Is it need to make prototype to prevent memory leak?
No. Unless you are doing something to keep a reference to the inside the function (or the array specifically) open, then it will get garbage collected.
The most efficient way to create new array is not:
var something = new Array();
but rather:
var something = [];
You should use then something similar to:
var variable_need = [
0x3131, 0x3132, 0x3134, 0x3137, 0x3138, 0x3139,
0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147,
0x3148, 0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e
];
Is "variable_need" generated every time when "function_to_call" called?
Yes.
If "function_to_call" called frequently... Is it need to make prototype to prevent memory leak?
There is no memory leak as long as you are not creating any closures. (Can't say from the posted code, what is 'v'?). But there will be a lot of memory allocation and deallocation. Better you move *variable_need* outside the function.
精彩评论