I’m trying to optimize a small web application’s use of JavaScript variables. I have about five functions that each produce an Ajax call, and repeatedly make use of a query string. Should I declare the query variable inside of each function, or will it increase efficiency to declare it globally? A very simple example of what I’m talking about is:
Local Declaration
<script type="text/javascript">
function queryOne() {
var queryString = "query arguments";
}
function queryTwo() {
var queryString = "query arguments";
}
</script>
Global Declaration
<script type="text/javascript">
var queryString;
function queryOne() {
queryString = "query arguments";
}
function queryTwo() {
queryString = "query arguments";
}
</script>
Is there are notable efficiency benefit to using the global declaration scheme?
Should be declared locally, as any global declaration will take extra time to look for the variable in the local scope and then the global scope, making the global declaration actually slower. Plus a variable declaration might not require a search for the variable name, it can simply just attempt to create a new variable.
Also, if code were added in the future, declaring the variable globally could cause it to be overwritten by other code or conflict.
Actually you might save a little time with a module level variable, if the query string is only assigned to once. However, if you are reassigning the query variable each time the function is called, then you definitely save time making the query variable local to each function.