[·Òë]High Performance JavaScript(021)
Splitting Up Tasks ·Ö½âÈÎÎñ
What we typically think of as one task can often be broken down into a series of subtasks. If a single function is taking too long to execute, check to see whether it can be broken down into a series of smaller functions that complete in smaller amounts of time. This is often as simple as considering a single line of code as an atomic task, even though multiple lines of code typically can be grouped together into a single task. Some functions are already easily broken down based on the other functions they call. For example:
ÎÒÃÇͨ³£½«Ò»¸öÈÎÎñ·Ö½â³ÉһϵÁÐ×ÓÈÎÎñ¡£Èç¹ûÒ»¸öº¯ÊýÔËÐÐʱ¼äÌ«³¤£¬ÄÇô²é¿´ËüÊÇ·ñ¿ÉÒÔ·Ö½â³ÉһϵÁÐÄܹ»¶Ìʱ¼äÍê³ÉµÄ½ÏСµÄº¯Êý¡£¿É½«Ò»ÐдúÂë¼òµ¥µØ¿´×÷Ò»¸öÔ×ÓÈÎÎñ£¬¶àÐдúÂë×éºÏÔÚÒ»Æð¹¹³ÉÒ»¸ö¶ÀÁ¢ÈÎÎñ¡£Ä³Ð©º¯Êý¿É»ùÓÚº¯Êýµ÷ÓýøÐвð·Ö¡£ÀýÈ磺
function saveDocument(id){
//save the document
openDocument(id)
writeText(id);
closeDocument(id);
//update the UI to indicate success
updateUI(id);
}
If this function is taking too long, it can easily be split up into a series of smaller steps by breaking out the individual methods into separate timers. You can accomplish this by adding each function into an array and then using a pattern similar to the array-processing pattern from the previous section:
Èç¹ûº¯ÊýÔËÐÐʱ¼äÌ«³¤£¬Ëü¿ÉÒÔ²ð·Ö³ÉһϵÁиüСµÄ²½Ö裬°Ñ¶ÀÁ¢·½·¨·ÅÔÚ¶¨Ê±Æ÷Öе÷Óá£Äã¿ÉÒÔ½«Ã¿¸öº¯Êý¶¼·ÅÈëÒ»¸öÊý×飬ȻºóʹÓÃǰһ½ÚÖÐÌáµ½µÄÊý×é´¦Àíģʽ£º
function saveDocument(id){
var tasks = [openDocument, writeText, closeDocument, updateUI];
setTimeout(function(){
//execute the next task
var task = tasks.shift();
task(id);
//determine if there's more
if (tasks.length > 0){
setTimeout(arguments.callee, 25);
}
}, 25);
}
 
Ïà¹ØÎĵµ£º
[ת×Ô]http://article.yeeyan.org/view/mouse4x/16540
JSON±»¹«ÈÏΪä¯ÀÀÆ÷ÖÐXMLµÄºó¼ÌÕߣ¬ËüµÄÄ¿±ê½ö½öÊdzÉΪһÖÖ¼òµ¥¡¢ÓÅÑŵÄÊý¾Ý¸ñʽ£¬ÒÔ·½±ãä¯ÀÀÆ÷ºÍ·þÎñÆ÷Ö®¼äµÄÊý¾Ý½»»»¡£ÔÚÍê³ÉÕâÒ»¼òµ¥ÈÎÎñµÄ¹ý³ÌÖУ¬Ëü½«ÒýÁìÏÂÒ»´úÍòÎ¬Íø¡£
¶ÔÏó¼ò½é
¿´,Õâ¾ÍÊÇÒ»¸ö¶ÔÏó:
var myFirstObject ={};
¾¡¹Ü¿´ÆðÀ´Í¦¼òµ¥£¬È»¶øÄÇЩ» ......
function total(){
var i=0;
for(j=1;j<=20;j++)
{
var step="step"+j;
if(document.getElementById(step)){
if(document.getElementById(step).checked==true)
{
i=i+parseInt(document.getElementById(step).value);
}
}
}
document.getElementById("total").innerHTML = i;
}
function Resetvalue(){
......
Conditionals Ìõ¼þ±í´ïʽ
Similar in nature to loops, conditionals determine how execution flows through JavaScript. The traditional argument of whether to use if-else statements or a switch statement applies to JavaScript just as it does to other languages. Since different b ......
Regular Expression Optimization ÕýÔò±í´ïʽÓÅ»¯
Incautiously crafted regexes can be a major performance bottleneck (the upcoming section, "Runaway Backtracking" on page 91, contains several examples showing how severe this can be), but there is a lot you can do to improve re ......