[·Òë]High Performance JavaScript(014)
Recursion Patterns µÝ¹éģʽ
When you run into a call stack size limit, your first step should be to identify any instances of recursion in the code. To that end, there are two recursive patterns to be aware of. The first is the straightforward recursive pattern represented in the factorial() function shown earlier, when a function calls itself. The general pattern is as follows:
µ±ÄãÏÝÈëµ÷ÓÃÕ»³ß´çÏÞÖÆÊ±£¬µÚÒ»²½Ó¦¸Ã¶¨Î»ÔÚ´úÂëÖеĵݹéʵÀýÉÏ¡£Îª´Ë£¬ÓÐÁ½¸öµÝ¹éģʽֵµÃ×¢Òâ¡£Ê×ÏÈÊÇÖ±½ÓµÝ¹éģʽΪ´ú±íµÄÇ°ÃæÌáµ½µÄfactorial()º¯Êý£¬¼´Ò»¸öº¯Êýµ÷ÓÃ×ÔÉí¡£ÆäÒ»°ãģʽÈçÏ£º
function recurse(){
recurse();
}
recurse();
This pattern is typically easy to identify when errors occur. A second, subtler pattern involves two functions:
µ±·¢Éú´íÎóʱ£¬ÕâÖÖģʽ±È½ÏÈÝÒ×¶¨Î»¡£ÁíÍâÒ»ÖÖģʽ³ÆÎª¾«ÇÉģʽ£¬Ëü°üº¬Á½¸öº¯Êý£º
function first(){
second();
}
function second(){
first();
}
first();
In this recursion pattern, two functions each call the other, such that an infinite loop is formed. This is the more troubling pattern and a far more difficult one to identify in large code bases.
ÔÚÕâÖֵݹéģʽÖУ¬Á½¸öº¯Êý»¥Ïàµ÷ÓöԷ½£¬ÐγÉÒ»¸öÎÞÏÞÑ»·¡£ÕâÊÇÒ»¸öÁîÈ˲»°²µÄģʽ£¬ÔÚ´óÐÍ´úÂë¿âÖж¨Î»´íÎóºÜÀ§ÄÑ¡£
Most call stack errors are related to one of these two recursion patterns. A frequent cause of stack overflow is an incorrect terminal condition, so the first step after identifying the pattern is to validate the terminal condition. If the terminal condition is correct, then the algorithm contains too much recursion to safely be run in the browser and should be changed to use iteration, memoization, or both.
´ó¶àÊýµ÷ÓÃÕ»´íÎóÓëÕâÁ½ÖÖģʽ֮һÓйء£³£¼ûµÄÕ»Òç³öÔÒòÊÇÒ»¸ö²»ÕýÈ·µÄÖÕÖ¹Ìõ¼þ£¬ËùÒÔ¶¨Î»Ä£Ê½´íÎóµÄµÚÒ»²½ÊÇÑéÖ¤ÖÕÖ¹Ìõ¼þ¡£Èç¹ûÖÕÖ¹Ìõ¼þÊÇÕýÈ·µÄ£¬ÄÇôËã·¨°üº¬ÁËÌ«¶à²ãµÝ¹é£¬ÎªÁËÄܹ»°²È«µØÔÚä¯ÀÀÆ÷ÖÐÔËÐУ¬Ó¦µ±¸ÄÓõü´ú£¬ÖÆ
Ïà¹ØÎĵµ£º
var
xmlDoc
=
null
;
function
parseXML
(
xmlUrl
)
{
¡¡¡¡try
{
¡¡¡¡¡¡¡¡//IE
¡¡¡¡¡¡¡¡xmlDoc
=
new
ActiveXObject
(
"Microsoft.XMLDOM"
);
¡¡¡¡¡¡¡¡xmlDoc
.
async
=
false
;
¡¡¡¡¡¡¡¡xmlDoc
......
ÃæÏò¶ÔÏóµÄÓïÑÔ¶àÊý¶¼Ö§³Ö¼Ì³Ð£¬¼Ì³Ð×îÖØÒªµÄÓŵã¾ÍÊÇ´úÂ븴Ó㬴Ӷø¹¹½¨´óÐÍÈí¼þϵͳ¡£Èç¹ûÒ»¸öÀàÄܹ»ÖØÓÃÁíÒ»¸öÀàµÄÊôÐԺͻò·½·¨£¬¾Í³ÆÖ®Îª¼Ì³Ð¡£
´ÓÕâ¸ö½Ç¶ÈÀ´¿´¿´jsµÄ¼Ì³Ð·½Ê½¡£jsÖм̳з½Ê½ÓëдÀ෽ʽϢϢÏà¹Ø¡£²»Í¬µÄдÀ෽ʽÔì³É²»Í¬µÄ¼Ì³Ð·½Ê½¡£¸÷ÖÖÁ÷ÐÐjs¿â¼Ì³Ð·½Ê½Ò²¸÷²»Ïàͬ¡£´Ó×î¼òµ¥µÄ
¸´ÓÿªÊ¼¡£
1¡¢¹¹Ôìº ......
JavascriptÊý¾ÝÀàÐÍ
ÓÉÓÚjavascriptÊÇÈõÀàÐÍÓïÑÔ£¬¼´¶¨Òå±äÁ¿Ê±²»±ØÉùÃ÷ÆäÀàÐÍ
¡£µ«Õâ²¢²»Òâζ×űäÁ¿Ã»ÓÐÀàÐÍ¡£ÒòΪ¸³ÖµÊ±»á×Ô¶¯Æ¥ÅäÊý¾ÝÀàÐÍ£¡
ĿǰÓõ½µÄ»ù±¾Êý¾ÝÀàÐÍ
number
boolean
string
var i
i="test";//Õâʱi¾Í³ÉÁËstringÀàÐÍ
var i
i=4;//Õâʱi¾Í³ÉÁËnumberÀàÐÍ
³£ÓöÔÏóÀàÐÍ<object> ......
µÚËÄÕ Algorithms and Flow Control Ëã·¨ºÍÁ÷³Ì¿ØÖÆ
The overall structure of your code is one of the main determinants as to how fast it will execute. Having a very small amount of code doesn't necessarily mean that it will run quickly, and having a large amount of code ......