Share an optimization technique for writing functions in Javascript.
Applicable functions should meet the following conditions:
Produce fixed results
Multiple calls on the page
Complex or time-consuming
The code and analysis are as follows :
Java code:
// Functions that produce fixed results and are called multiple times on the page
function check() {
//Simulate time-consuming operations
var begin = Date.now(); //Added by ECMAScript5, if not supported Please change to new Date();
var ONE_SECOND = 1000,
result = false;
while(true) {
if(Date.now() - begin >= ONE_SECOND){
result = true;
break;
}
}
//Function rewrite, return the result directly
check = function() {
return result;
}
return result;
}
var firstBegin = Date.now();
check(); //First function call
var firstEnd = Date.now();
check(); //The second function call
var secondEnd = Date.now();
console.log("The first function takes time:" (firstEnd - firstBegin) "ms.");
console.log("The second function takes time:" (secondEnd - firstEnd) "ms.");
The results are displayed as follows:
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn