JavaScript Optimization: How to Improve Your Code Performance and Quality?

JavaScript is a dynamic, weakly typed, interpreted language. Its flexibility and expressiveness make it one of the most popular languages ​​in Web development. However, these features also bring some disadvantages, such as code readability, maintainability, testability and performance issues. So, how to optimize JavaScript and improve the performance and quality of your code? Here are some common suggestions, along with some sample code, that I hope will be helpful to you.

1. Use strict mode.

  • Strict mode can avoid some implicit errors and unsafe behaviors, such as variable promotion, global variable pollution, implicit type conversion, etc., making the code more standardized and clear. To use strict mode, just add this line to your code file or function "use strict";. For example:

"use strict"; // 开启严格模式

x = 10; // ReferenceError: x is not defined
delete Object.prototype; // TypeError: Cannot delete property 'prototype' of function Object() { [native code] }
var obj = {};
Object.defineProperty(obj, "a", {value: 1, writable: false});
obj.a = 2; // TypeError: Cannot assign to read only property 'a' of object '#<Object>'

2. Use modern syntax features

  • ES6 and later versions provide many new syntax features for JavaScript, such as let and const declarations, arrow functions, template strings, destructuring assignments, spread operators, classes, modules, etc. These features can make your code more concise, Elegant and easy to understand. To use these features, you may need a transpilation tool, such as Babel, to convert your code into code that is compatible with more browsers and environments. For example:

// 使用let和const声明变量,避免var带来的作用域和提升问题
let x = 10; // 块级作用域
const y = 20; // 常量

// 使用箭头函数,简化函数定义和this绑定
const add = (a, b) => a + b; // 无需function关键字和return语句
const arr = [1, 2, 3];
arr.map(x => x * 2); // 简洁的回调函数
const obj = {
  name: "Alice",
  sayHello: () => {
    console.log(`Hello, ${this.name}`); // this指向obj
  }
};

// 使用模板字符串,方便拼接字符串和插入变量
const name = "Bob";
const greeting = `Hello, ${name}`; // 使用反引号和${}语法
console.log(greeting); // Hello, Bob

// 使用解构赋值,方便从数组或对象中提取值
const [a, b, c] = [1, 2, 3]; // 数组解构
console.log(a, b, c); // 1 2 3
const {name, age} = {name: "Charlie", age: 18}; // 对象解构
console.log(name, age); // Charlie 18

// 使用展开运算符,方便合并数组或对象
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2]; // 数组展开
console.log(arr3); // [1, 2, 3, 4, 5, 6]
const obj1 = {name: "David", age: 20};
const obj2 = {gender: "male", hobby: "coding"};
const obj3 = {...obj1, ...obj2}; // 对象展开
console.log(obj)

3. Reduce global variables

Global variables are variables defined in the global scope and can be used anywhere in the code. However, using too many global variables increases namespace and memory consumption, so the use of global variables should be avoided if possible. Variables and functions can be restricted to a desired scope, for example using closures to protect variables. For example, the following code limits the variable i and function foo inside an anonymous function, thus avoiding the creation of global variables:

(function() {
  var i = 0;

  function foo() {
    // some code
  }
})();

4. Optimize loop

Loops are one of the most commonly used operations in JavaScript, so optimizing loops can significantly improve the performance of your code. Here are some tips for optimizing loops:

  • Avoid doing multiple calculations in a loop. If the result of the calculation is not going to change, you can do the calculation before the loop and save the result in a variable.

For example, the following code calculates the value of array[i] in a loop, which will cause performance issues if the array is large:

var array = [1, 2, 3, 4, 5];
for (var i = 0; i < array.length; i++) {
console.log(array[i] * 2);
}

可以通过在循环之前计算阵列
var array = [1, 2, 3, 4, 5];
    for (var i = 0; i < array.length; i++) {
      var value = array[i] * 2;
      console.log(value);
    }

Use a reverse loop. In a reverse loop, starting from the end of the array can reduce the number of loops and improve the performance of the code.

For example, the following code uses a forward loop to traverse an array, which causes the code execution time to increase:

var array = [1, 2, 3, 4, 5];
for (var i = 0; i < array.length; i++) {
  console.log(array[i]);
}

You can use reverse order loops to optimize your code:

var array = [1, 2, 3, 4, 5];
for (var i = array.length - 1; i >= 0; i--) {
  console.log(array[i]);
}

Use forEach() method. forEach() is a built-in method of JavaScript arrays that iterates through the array and performs a specified function on each element. Using the forEach() method can simplify the code and improve the readability and performance of the code.

For example, the following code uses a for loop to iterate through an array and perform a function on each element:

var array = [1, 2, 3, 4, 5];
for (var i = 0; i < array.length; i++) {
  console.log(array[i]);
}

You can use the forEach() method to optimize your code:

var array = [1, 2, 3, 4, 5];
array.forEach(function(value) {
  console.log(value);
});
var array = [1, 2, 3, 4, 5];
array.forEach(function(value) {
  console.log(value);
});

5. Avoid unnecessary DOM operations

DOM operation is an expensive operation, and unnecessary DOM operations should be avoided as much as possible. Code can be optimized using caching DOM elements and minimizing DOM operations.

For example, the following code queries DOM elements each time through the loop, which causes performance issues:

var items = document.getElementsByTagName('li');
  for (var i = 0; i < items.length; i++) {
  var item = items[i];
  item.style.backgroundColor = 'red';
  }

You can optimize your code by querying the DOM elements before looping and saving the results in a variable:

var items = document.getElementsByTagName('li');
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.style.backgroundColor = 'red';
}

6. Use event delegation

Event delegation is a common technique that reduces the number of event handlers and improves the performance and maintainability of your code. Event delegation works by attaching an event handler to a parent element and then handling the event based on the event's target.

For example, the following code adds an event handler for each button, which results in verbose code and performance issues:

var buttons = document.getElementsByTagName('button');
    for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.addEventListener('click', function() {
    console.log('Button clicked');
    });
    }

You can use event delegation to optimize your code:

var container = document.getElementById('container');
    container.addEventListener('click', function(event) {
    if (event.target.tagName === 'BUTTON') {
    console.log('Button clicked');
    }
    });

7. Use caching and throttling

Caching and throttling are two common techniques that can optimize the performance of your code. Caching can avoid double calculations by saving the calculation results in a variable. Throttling can reduce the amount of event processing by limiting the frequency with which functions are called.

For example, the following code calculates a value every time you scroll, which can cause performance issues:

window.addEventListener('scroll', function() {
    var value = calculateValue();
    console.log(value);
    });

You can use caching to optimize your code:

var value = calculateValue();
window.addEventListener('scroll', function() {
  console.log(value);
});

Additionally, throttling can be used to limit the number of event handlers:

var value = calculateValue();
window.addEventListener('scroll', throttle(function() {
  console.log(value);
}, 100));

8. Use appropriate data structures

Data structures can improve the performance and maintainability of your code. Choosing the right data structures can optimize your code and reduce development and maintenance costs.

For example, the following code uses an array to store a set of data and uses the indexOf() method to find elements:

var data = [1, 2, 3, 4, 5];
  var index = data.indexOf(3);
  console.log(index)

You can use an object to store the data and use property names to find elements:

var data = {

    '1': true,
    '2': true,
    '3': true,
    '4': true,
    '5': true
    };
    var exists = data['3'];
    console.log(exists);

9. Reduce network requests

Network requests are an expensive operation and should be minimized. Can use HTTP

For example, the following code requests data from the server every time the page loads, which causes performance issues:

var data = fetchDataFromServer();

You can use HTTP buffering

var data = fetchDataFromCache();
if (!data) {
  data = fetchDataFromServer();
  saveDataToCache(data);
}

10. Use asynchronous programming

Asynchronous programming is a common technique that improves the performance and maintainability of your code. Asynchronous programming can be implemented using technologies such as callback functions, Promise, and async/await.

For example, the following code blocks the UI thread, causing performance issues:

var data = fetchDataFromServer();
renderData(data);

You can use callback functions to optimize your code:

fetchDataFromServer(function(data) {
  renderData(data);
});

In addition, you can use technologies such as Promise and async/await to optimize the code:

fetchDataFromServer()
  .then(function(data) {
    renderData(data);
  })
  .catch(function(error) {
    console.error(error);
  });

async function fetchDataAndRender() {
  try {
    var data = await fetchDataFromServer();
    renderData(data);
  } catch (error) {
    console.error(error);
  }
}

11. Use tools and frameworks

Using tools and frameworks can improve development efficiency and code quality. Code can be optimized using tools and frameworks such as code analysis tools, build tools, and testing frameworks.

For example, the following code uses ESLint for code analysis, Webpack for code packaging and optimization, and Jest for unit testing:

// .eslintrc.js
module.exports = {
  extends: 'eslint:recommended',
  env: {
    browser: true,
    es6: true,
    node: true
  },
  rules: {
    'no-console': 'off',
    'no-unused-vars': 'warn'
  }
};

// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ],
  devServer: {
    contentBase: path.join(__dirname, 'public'), port: 3000, hot: true, open: true
   };
   }

12. Write optimized CSS

CSS can also be optimized, thereby improving the performance of the page. You can write optimized CSS using techniques such as CSS selectors, style abbreviations, and CSS preprocessors.

For example, the following code uses CSS selectors to optimize CSS:

ul li a {
  color: #ff0000;
  font-size: 16px;
}

可以使用样式缩写来优化CSS:

font: 16px/1.5 'Helvetica Neue', sans-serif; color: #ff0000;

另外,可以使用CSS预处理器来编写优化的CSS。例如,以下代码使用Sass编写CSS:

����−����:16��;

487f5191191fdd8c27f7a9dcd6f25980.png

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/132769875