[Change] how to improve the operating speed of the JavaScript function articles (2)

This is Nicholas discuss efforts to prevent loss of control of the second script, mainly discussed how to reconstruct nested loops, recursion, and those who perform many functions within the same sub-operation of the function. The basic idea, and on a chunk () the same example, if several operations without a specific order of execution, and another is not a dependency, we can call an asynchronous manner through the implementation, not only can reduce the number of times, but also to prevent the script out of control. This article also introduces the technology to replace recursion by memoization approach.

【Original Title Speed up your JavaScript, Part 2
】 【Original author Nicholas C. Zakas

The following is the text of the translation:

Last week I was " too much happening in a loop "(translation: how to improve the operating speed of the cycle of JavaScript articles (1)) This article introduces the JavaScript to run the first reason for too long. Similar situation sometimes occurs in the function definition, function may also be because of improper use overload use. Is a function usually contains too many cycles (not implemented in the loop too much content), too much recursion, or just too much irrelevant, but also with the implementation of the operation.

Too often is a nested loop form, this code will always be occupied until the cycle end of the JavaScript engine. It has a very well-known example is the use of bubble sort algorithm. Because JavaScript has built-in sort () method, we do not need to use the sort in this way, but we can understand the nested loop algorithm with the crux of occupied resources, so as to avoid occurrence of similar situations. The following is a bubble sort method in JavaScript using a typical example:

function bubbleSort(items) {
for (var i = items.length - 1; i >= 0; i--) {
   for (var j = i; j >= 0; j--) {
       if (items[j] < items[j - 1]) {
           var temp = items[j];
           items[j] = items[j - 1];
           items[j - 1] = temp;

Recall your school's computer knowledge, you may recall Bubble sort is one of the least efficient sorting algorithm, because for an array containing n elements, must be carried out n times the square of the cycle of operation. If the number of elements in the array is very large, then the operation will last a long time. Inner loop operation is very simple, just for comparison and exchange of value, resulting in the maximum number of times because the loop. This will cause the browser to run the exception, the potential is the direct result of the warning dialog box that script out of control.

A few years ago, Yahoo's researcher Julien Lecomte wrote an article entitled " Running CPU Intensive JavaScript Computations in a Web Browser "in the article, described in this article on how to operate large javaScript divided into several small parts. One example is the bubble sort method into several steps, each step only one array traversal. I have made improvements to his code, but the method of thinking is still the same:

function bubbleSort(array, onComplete) {
var pos = 0; (function() {
   var j, value;
   for (j = array.length; j > pos; j--) {
       if (array[j] < array[j - 1]) {
           value = data[j];
           data[j] = data[j - 1];
           data[j - 1] = value;
   if (pos < array.length) {
       setTimeout(arguments.callee, 10);
   } else {

This function is asynchronous with a manager to achieve the bubble algorithm traverse the array before each pause. onComplete () function will be completed in order to trigger the array, suggesting that user data is ready. bubbleSort () function is used and the chunk () function is the same basic technology (see my previous post), will conduct wrapped in an anonymous function, the arguments.callee passed to the setTimeout () to repeat the operation to achieve the purpose of until sorting complete. If you want to disassemble the nested loop into several small steps to achieve the objective of the liberation of the browser, this function provides a good guidance.

Similar problems included excessive recursion. Each additional recursive calls will use more memory, thus slowing down the browser to run. Annoying, you can send the script out of control in the browser warning before the system would run out of memory, causing the browser to stop responding in the state. Crockford has a blog on this issue conducted in-depth discussion. He was the example used, is to use recursion to generate a Fibonacci series.
function fibonacci(n) {
return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);

In accordance with Crockford's view, the implementation of fibonacci (40) this statement will be repeated calls itself 331 160 280 times. Avoid the use of one of the options is to use recursive memoization technique, this technology can get the last call to the implementation of the results. Crockford introduced following the function, value function can be increased to deal with this feature:

function memoizer(memo, fundamental) {
var shell = function (n) {
   var result = memo[n];
   if (typeof result !== 'number') {
       result = fundamental(shell, n);
       memo[n] = result;
   return result;
return shell;

He then applied this function Fibonacci series generator at:

var fibonacci = memoizer([0, 1],
function(recur, n) {
  return recur(n - 1) + recur(n - 2);

Then again, if we call fibonacci (40), only repeated calls 40 times, and increase very much compared to the original. memoization principle, summed up the word, the same result, you do not need to calculate twice. If a result you may re-use, this results are saved, than to recalculate the time to the quick.

The last possible reason for the slow implementation of a function that we mentioned before, the function of which performed much of the content, usually because of the use of the development model similar to the following:

function doAlot() {

Here are three different functions to perform, please note that whatever the function, in the implementation process is not dependent on other functions, they are relatively independent in nature, but requires a specific time to go in the implementation of it. Also, you can use a similar chunk () method to perform a series of functions, and will not lead to lock the browser.

function schedule(functions, context) {
setTimeout(function() {
   var process = functions.shift();;
   if (functions.length > 0) {
       setTimeout(arguments.callee, 100);

schedule function has two parameters, one is included to perform the function of the array, the other is labeled the context of this object belongs. Function of the realization of the array to the queue, Timer event is triggered each time the queue will be out front and perform a function, this function can be a function the following manner:
schedule([doSomething, doSomethingElse, doOneMoreThing], window);

Very much hope that the libraries have increased in all JavaScript like this process handler. YUI 3.0 has been introduced when the Queue object, you can call a timer function continuously.

Whether existing technology can help us to split the complex process to what extent, for developers to use this method to understand and identify bottlenecks in the script out of control is very important. Whether the cycle of too many, recursive, or something else, you should know if handled similar situations. But remember, the technology and functions mentioned here only, serve in the actual application, you should be to improve on them, so as to play a greater role.
标签: lt, implementation, javascript function, nicholas c, execution, occurrence, translation, typical example, sort method, crux, recursion, bubble sort algorithm, javascript engine, chunk, loop algorithm, javascript articles, asynchronous manner
分类: Web
时间: 2010-08-02


  1. [Change] how to improve the operating speed of the cycle of JavaScript articles (1)

    According to Nicholas to say, there are four kinds of code will slow down the script to run, and eventually th ...
  2. [Change] how to improve the operating speed of the recursive JavaScript articles (3)

    Affect the performance of another killer JavaScript is recursive, is mentioned in the previous section can be ...
  3. (To) how to improve the operating speed of JavaScript (DOM articles) We all know, DOM operation efficiency is very low, slow and not general, but this i ...
  4. Ajax improve client response speed skills

    The emergence of AJAX greatly changed the Web application client mode of operation, which allows users to work ...
  5. How to Improve Lucene indexing speed (rpm)

    Original Address This article introduces how to improve Lucene's indexing speed. Describes most of the ideas a ...
  6. MySQL to improve the operating efficiency of the strategy for data loading

    Transfer from: When interest is to optimize the multi-SELECT ...
  7. How to improve database query speed (excerpt) - turn

    1, with the program, Ensure the realization of the basis functions to minimize the number of visits to the dat ...
  8. Any industry that can improve the operating performance for the common platform

    Any industry that can improve the operating performance for the common platform OSI soft products PI System ™ ...
  9. What to do to improve site access speed optimization

    What to do to improve site access speed optimization First, the server optimization l Windows Series: 64 Win20 ...
  10. The way to Improve Your Page Speed for Better Search Engine Ranking

    Half of a web design should be how to improve your page speed for better search engine rankings. The simplest ...
  11. Improve the operating efficiency of the method of PHP

    [Transfer] PHP is one of the advantages of fast web applications for the general can be said enough. However, ...
  12. [Turn] to use gzip, deflate compression to improve web browsing speed web

    Web site access speed is determined by multiple factors together, these factors such as application response t ...
  13. Database query optimization (one million record deal on how to improve the processing speed of queries)

    1 the query is optimized, should try to avoid full table scans, we should first consider where and order by th ...
  14. Handling of millions of queries a database to improve the processing speed

    1. On the query optimization , to avoid full table scans, should first consider where and order by columns inv ...
  15. How to improve your access speed

    Google code today to stroll when the unexpected windfall, found it a very good web analytics components: Page ...
  16. Memory database to improve the response speed of web services

    My case is like this, a central database and web services, the amount of data is about 10 million rows, eight ...
  17. MyEclipse startup and operating speed of the optimization

    A collection of some of the memory consumption on the settlement of the MyEclipse way, tested very effective, ...
  18. [Change] Comparison of the four operating mode XML

    1. Introduction 1) DOM (JAXP Crimson parser) DOM is platform-and language-independent manner, said the officia ...
  19. [Change] How to improve the site Baidu snapshot of time

    Baidu snapshot of the update frequency, site weight with seo closely related, and its importance is not much h ...