How to improve the speed of JavaScript functions

Source: Internet
Author: User
Tags array sort sort

Nicholas explains how to improve the speed of JavaScript functions!

This is Nicholas. The second article, which prevents the script from getting out of control, mainly discusses how to refactor nested loops, recursion, and those functions that perform many child operations simultaneously within a function. The basic idea is consistent with the example in the previous section trunk (), if several operations do not have a specific order of execution and are not dependent on each other, we can execute asynchronously, not only to reduce the number of executions, but also to prevent the script from getting out of control. This paper also introduces the method of replacing recursion by Memoization technology.

"Original title" Speed Up Your JavaScript, part 2

"Original author" Nicholas C. Zakas

Last week I introduced the first reason that JavaScript ran too long in the article "too much happening in a loop". Similar situations sometimes appear in the definition of functions, and functions may also be overloaded because of improper use. Typically, there are too many loops in the function (not too much in the loop), too many recursion, or just too many unrelated operations to do together.

Too many loops are often nested, and this code takes up the JavaScript engine until the loop ends. A very famous example of this is the use of a bubble algorithm to sort. Since JavaScript has a built-in sort () method, we don't need to sort by this way, but we can use this algorithm to understand the crux of the nesting of resources, thus avoiding similar occurrences. The following is a typical example of using bubble sorting in javascript:

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 the computer knowledge you learned at school, and you may remember bubble sort is one of the least efficient sort algorithms, because for an array that contains n elements, you must do a cyclic operation of N squared. If the number of elements in the array is very large, then this operation lasts a long time. The internal loop operation is simple, but is responsible for comparing and exchanging numeric values, the biggest cause of the problem is the number of times the loop executes. This causes the browser to run an exception, and the potential immediate result is the warning dialog box that the script is out of control.

A few years ago, Yahoo researcher Julien Lecomte wrote an article titled "Running CPU Intensive JavaScript computations in a Web Browser", In this article, the authors describe how to break down a large number of JavaScript operations into small pieces. One example is the decomposition of the bubble sort into multiple steps, with each step traversing only one array at a time. I've made improvements to his code, but the approach 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;
}
}
pos++;
if (pos < array.length) {
setTimeout(arguments.callee, 10);
} else {
onComplete();
}
})();
}

This function uses an asynchronous manager to implement the bubble algorithm, pausing before each traversal of the array. The OnComplete () function fires after the array sort completes, prompting the user that the data is ready. The Bubblesort () function uses the same basic techniques as the chunk () function (referring to my previous post), wrapping the behavior in an anonymous function, passing the Arguments.callee to settimeout () for repeated operations until the sorting is complete. This function provides good guidance if you want to disassemble a nested loop into a few small steps to unlock the browser's purpose.

Similar problems include excessive recursion. Each additional recursive call consumes more memory, slowing the browser down. It is annoying that you may run out of memory before the browser emits a script out of control warning, causing the browser to stop responding. Crockford has had an in-depth discussion on this issue on his blog. The example he used was to generate a Fibonacci sequence with recursion.

function fibonacci(n) {
return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.