Home  >  Article  >  Web Front-end  >  Analysis of methods to detect the most efficient functional features in JavaScript

Analysis of methods to detect the most efficient functional features in JavaScript

coldplay.xixi
coldplay.xixiforward
2020-06-23 12:48:382087browse

Analysis of methods to detect the most efficient functional features in JavaScript

Code execution efficiency is crucial to both programmers and programs, especially when encountering function methods that require a large number of calls and repeated calls. In many Javascript frameworks you can see functions that are called repeatedly. When using these frameworks, we must be careful to write optimized code as much as possible. One way to optimize your code is to use a test statement before creating the function, rather than executing it every time the function is called. Let's look at a simple example below.

Bad way of writing

The following way of writing is relatively not so optimized and efficient:

function something() {
    if('something' in obj) {
        // something
    }
    else {
        // fallback
    }
}

The reason why the above code is not very efficient is that every function call , the judgment condition must be executed once. Let's improve it:

Optimized code

Instead of executing the judgment condition every time the function is called, it is better to execute the judgment statement first and then create the function:

var something = ('something' in obj) ? function() {
    // something
} : function() {
    // fallback
};

This This mode is especially effective when judging whether a browser has a certain feature function, because the target feature of the judgment is unlikely to change subsequently. Although the execution speed of such judgment statements is very fast, there is no reason for you to execute them multiple times. In short, develop good coding habits and avoid repeated code!

Recommended tutorial: "javascript basic tutorial"

The above is the detailed content of Analysis of methods to detect the most efficient functional features in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:webhek.com. If there is any infringement, please contact admin@php.cn delete