How to write efficient JavaScript JS performance optimization Tips

Source: Internet
Author: User
Tags arrays benchmark bitwise bitwise operators variable scope

This article discusses JavaScript performance optimization.

Firefox has the fastest JavaScript parser SpiderMonkey, with a variety of efforts to make JavaScript faster, one of which is asm.js. Asm.js is a subset of JavaScript that is produced by Emscripten, which makes a lot of optimizations for the JavaScript code that is compiled by C/s + +, which is hard to look at after compiling code, which is why you can't write the optimized code yourself, but it runs very fast. I suggest you read this article

Well, our goal is to write faster JavaScript code, and here are some tips for getting your code to run faster and better memory efficiency. Notice that I'm not strictly talking about DOM and Web applications, it's about JavaScript, Dom is just part of it.

Seeing is believing, I'm adding the first jsperf test case to add, using the Firefox38 and Chrome39 tests.

No type conversions

JavaScript is a dynamic type, but if you want to improve speed do not use this feature. Try to keep the type of the variable consistent. This also applies to arrays, although it is primarily optimized by browsers, but try not to mix different types of arrays. This is one of the reasons why C + + code compiled into JavaScript uses static types.

{
var x = ' 2 ';
var y = 5;
x = 2;
x + y;
}

Test Cases

Also: converting between strings and numeric types

For example, do you have to convert a string to a number, parseint and parsefloat are the best ways to do it? Let's take a look.

parsefloat ("100")
+ "100"
Integral type
parseint ("100", 10)
"100" |
">> 0"
"<< 0"
Valid for positive numbers only
">>> 0"

parseint Test ~ parsefloat Test

Firefox is optimized for bitwise operations, running code that is about 99% faster than parseint and + operations. Chrome obviously has no preference for bitwise operators, and they are 62% slower than the parseint function.

The parsefloat + operator is faster on both browsers (Firefox 28%,chrome 39%).

So, what if you're writing node/chrome or Firefox apps? I think it is correct to use the parseint function in general.

do not reconstruct objects

Reorganizing objects is not cheap and should be avoided:

Do not use the delete operator

A delete operation is much slower than assigning a null property. Allocating NULL in two browsers is fast 99%, but it cannot modify the structure of the object, but the deletion can.

Editor: I think this is a bit misleading, which doesn't mean you shouldn't use the delete operator, the delete operator has its own usage, and it protects against memory leaks from objects.

Delete vs null

Do not add attributes later

Try not to add attributes at a later time, preferably by defining the schema of the object from the outset. This is 100% faster in Firefox and 89% faster in Chrome.

Dynamic Properties VS Predefined structures

#3字符串联连

String connection is a very expensive operation, but what should be done? Of course not Array.prototype.join.

The + = operator seems to be much faster than +, and String.prototype.concat and Array.prototype.join are faster in both browsers. Array.prototype.join is the slowest, in line with market expectations.

String Connection test

#4 Correct use of regular expressions

It's not necessary to use RegExp.prototype.exec, is it?

However, there is a performance difference between RegExp.prototype.test and String.prototype.search, so let's see which method is faster:

Methods of regular expressions

RegExp.prototype.exec is much faster than String.prototype.match, but they are not exactly the same thing, their differences beyond the scope of this article, see this question and answer.

RegEx.prototype.test is faster, probably because it does not return a matching index. String.prototype.search should only be used to find the matching index that you want.

However, you should not use regular expressions to find the location of another string, you can use the String.prototype.indexOf method.

String.prototype.search VS String.prototype.indexOf

Another interesting benchmark is String.prototype.indexOf VS RegExp.prototype.test, which I personally expect to be fast, something that happens in Firefox, but in Chrome, that's not the case. RegExp.prototype.test is 32% faster in Firefox and String.prototype.indexOf 33% in Chrome. In this case, you choose the way you like it.

#5 Limit declaration/Pass Variable Scope (scope)

If you call a function, the browser must do something called range lookup, which is more expensive depending on how many scopes it is looking for. Try not to get a global/high range of variables, try to make local range variables, and pass them to the function. Less range lookup, less sacrificing speed.

This test tells us that it is quicker to pass and use variables from a local scope than to look up variables from a higher declaration range, both Chrome and Firefox.

Internal scope vs High range vs global

#6 You don't need everything with jquery.

Most developers use jquery to do some simple tasks, I mean you don't need to use jquery on some occasions, do you think it's always necessary to use $.val ()? Just take this example:

$ (' input '). KeyUp (function () {
if ($ (this). val () = = ' blah ') {...}
});

This is one of the most important reasons to learn how to use JavaScript to modify the DOM so that you can write more efficient code.

Complete the same function with pure javascript100% 100% faster, this is JSPERF benchmark test

$ (' input '). KeyUp (function () {
if (this.value = = ' blah ') {...}
});

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.