惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
GbyAI
GbyAI
B
Blog RSS Feed
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
Last Week in AI
Last Week in AI
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
N
Netflix TechBlog - Medium
G
Google Developers Blog
博客园_首页
有赞技术团队
有赞技术团队
V
V2EX
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
MongoDB | Blog
MongoDB | Blog
H
Help Net Security
aimingoo的专栏
aimingoo的专栏
月光博客
月光博客
Hugging Face - Blog
Hugging Face - Blog
The GitHub Blog
The GitHub Blog
S
SegmentFault 最新的问题

Yusuf Aytas

When Code Is Cheap, Does Quality Still Matter? Why Crouching Tiger, Hidden Dragon Is a Masterpiece Why We Ignore Advice The Mirror Is Part of the Machine When Too Many Maps Overlap on One Person The Work Runs on Different Maps Your Work Introduces You Trial By Fire The Dude Why Headcount Math Lies Capacity Is the Roadmap The Roadmap Is Not the System Torres del Paine W Trek Escaping Status Theater Incentives Drive Everything Scaling Culture Without Dilution What Good Looks Like Why Airport Security Feels Random Why Politics Appear How to Work with Me The Janus Protocol Multi-Horizon Delivery Framework What Good Execution Looks Like Managing Your Manager Why Kingdom of Heaven’s Director’s Cut Is Better AI Broke Interviews Most of What We Call Progress Managers Have Been Vibe Coding All Along Stop Wasting Brainpower Why Over-Engineering Happens
Faster JavaScript
Yusuf Aytas · 2012-08-02 · via Yusuf Aytas

Published · 3 min read

JavaScript is a very important language for now and the future. Nowadays, there is no page that does not include some JavaScript code in it. Moreover, code written in JavaScript increases day by day. The more JavaScript code we have in our web pages, the worse performance we observe. This occurs because of some tricks in JavaScript as a language. In this writing, I will try to explain what are the problems and what possible solution we can have. Before going into detail, let me explain what I am going to talk about. The first one will be about scoping, second will be libraries and last one is DOM manipulation and properties.

JavaScript is a language that uses dynamic scoping. In each function, we have default scope variables (window, navigator, document) that are pushed onto our stack. After those, each local variable is pushed onto stack with a separate block. Using local scope variables is faster than the global scope variables. At that point, we prefer using local variables. Note that when creating a new variable, we should always use var, otherwise it becomes global.


function begin() {
  document.getElementById("div1");
  document.getElementById("div2");
  document.getElementById("div3");
}

function begin() {
  var doc = document;
  doc.getElementById("div1");
  doc.getElementById("div2");
  doc.getElementById("div3");
}

Furthermore, JavaScript provides closures where we can pass a variable to another function that is dynamically created. The variable comes from another scope, which may result in performance issues. Therefore, we should bind it to a local variable.


function addClick() {
  var div = document.getElementById("div1");
  div.addEventListener("click", function () {
    div.style.marginTop = "32px";
    div.style.color = "blue";
  }, false);
}

function addClick() {
  var div = document.getElementById("div1");
  div.addEventListener("click", function () {
    var localDiv = div;
    localDiv.style.marginTop = "32px";
    localDiv.style.color = "blue";
  }, false);
}

Our second point is JavaScript libraries. While libraries are helpful, they can become a bottleneck when performance matters. Iteration helpers such as each or foreach often create unnecessary function calls and stack frames compared to native loops.

Last but very important is DOM manipulation. Accessing deep properties such as element.style.color repeatedly slows execution. DOM access is expensive and should be minimized by caching references locally.

HTML collections such as those returned by getElementsByTagName are live and heavy. Repeated access to them is costly.


function updateDivs() {
  var divs = document.getElementsByTagName("div");
  for (var i = 0; i < divs.length; i++) {
    update(divs[i]);
  }
}

function updateDivs() {
  var divs = document.getElementsByTagName("div");
  for (var i = 0, length = divs.length; i < length; i++) {
    update(divs[i]);
  }
}

HTML updates are dynamic but costly. Creating and appending elements repeatedly forces layout recalculations. Instead, we can batch DOM changes using document fragments.


function appendDivs(element) {
  for (var i = 0; i < 10; i++) {
    var div = document.createElement("div");
    element.appendChild(div);
  }
}

function appendDivs(element) {
  var fragment = document.createDocumentFragment();
  for (var i = 0; i < 10; i++) {
    var div = document.createElement("div");
    fragment.appendChild(div);
  }
  element.appendChild(fragment);
}

The general idea is simple: use local variables, rely less on libraries when performance matters, and manipulate the DOM carefully.