Skip to main content

Writing Efficient JavaScript

Free2015-11-27#JS#JavaScript性能优化#js优化原则#js编码技巧

Some coding habits can make your code run faster. This article supplements some uncommon optimization principles.

1. Fastest Conditional Checks

When to Use if Statements

  • When there are 2 or fewer discrete values to check

  • When a large number of values can be easily divided into different ranges

When to Use switch Statements

  • When there are more than 2 but fewer than 10 discrete values to check

  • When the condition values are non-linear and cannot be divided into ranges

When to Use Array Lookups

  • When there are more than 10 values to check

  • When the result corresponding to each condition is a single value, rather than a series of operations

2. String Operations

String Concatenation

Modern browsers have optimized strings. If the strings are short (fewer than 20 characters) and the quantity is small (fewer than 1000), all browsers can complete the operation within 1ms using the + operator.

Therefore, using push + join to optimize string concatenation is no longer necessary. In most scenarios, directly using + is fine.

Trimming Strings

ES5 provides a native trim method. If it's not available in your environment, you can use the following fastest trim implementation:

function trim(text) {
    text = text.replace(/^\s+/, '');
    for (var i = text.length - 1; i >= 0; i--) {
        if (/\S/.test(text.charAt(i))) {
            text = text.substring(0, i + 1);
            break;
        }
    }

    return text;
}

Or a slightly slower but simpler version:

function trim(text) {
    return text.replace(/^\s+/, '').replace(/\s+$/, '');
}

3. Data Access

The following principles ensure efficiency:

  • Cache frequently accessed values in local variables

    For example: arr.length, DOMNode List

  • Shorten the scope chain

    Besides with, the catch block in try-catch also extends the scope chain (it adds an object at the top of the scope chain, which contains the exception object). Therefore, try not to include too much code in the catch block to minimize performance impact.

References

  • "High Performance Web Sites: Essential Knowledge for Front-End Engineers"

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment