Home  >  Article  >  Web Front-end  >  Function optimization techniques that produce fixed results in Javascript_javascript techniques

Function optimization techniques that produce fixed results in Javascript_javascript techniques

WBOY
WBOYOriginal
2016-05-16 17:43:291019browse

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:

Copy code The code is as follows:

// 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:
Function optimization techniques that produce fixed results in Javascript_javascript techniques
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