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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
LINUX DO - 最新话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Forbes - Security
Forbes - Security
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
W
WeLiveSecurity
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
News and Events Feed by Topic
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
Engineering at Meta
Engineering at Meta
PCI Perspectives
PCI Perspectives
Martin Fowler
Martin Fowler
T
The Exploit Database - CXSecurity.com
F
Full Disclosure
WordPress大学
WordPress大学
S
Security Affairs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
SegmentFault 最新的问题
P
Privacy International News Feed
IT之家
IT之家
M
MIT News - Artificial intelligence
G
GRAHAM CLULEY
Hacker News: Ask HN
Hacker News: Ask HN
D
DataBreaches.Net
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Check Point Blog
美团技术团队
Security Latest
Security Latest
Cyberwarzone
Cyberwarzone
N
News and Events Feed by Topic
MyScale Blog
MyScale Blog
H
Help Net Security
宝玉的分享
宝玉的分享
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
I
Intezer
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AI
AI
I
InfoQ
N
News | PayPal Newsroom
TaoSecurity Blog
TaoSecurity Blog

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 Prisoner's Dilemma Climbing No More The Weekly Win Mevlana Candy Brewing Turkish Tea Onboarding Your Engineering Manager Technical Deep Dives Yapay Zekâ Çağında Bilgisayar Mühendisliği Building Remote Teams From Idea to Launch in 2 Weeks Reflecting on Software Engineering Handbook Representing the Business New Manager Survival Guide Take Self Reviews Seriously Chasing Real Respect The Invisible Difference Learning the Johari Window Management is a Lonely Place Simple Task Management AI Balance in Work PIP Manager Insights Engineering Manager Interview Preparation Work-Life Balance as a Manager Bridging the Management Disconnect Tech Hiring Bubble Bursts Traits for EMs Simple Acts of Recognition Matter The Question I Ask Every New Report The Reality of an Employer's Market Bridging Ideals and Reality Hiring Red Flags Why The Godfather Is So Damn Good Subteam Tenets No Fluff Please Losing a Top Performer Balancing Act of Reliability Building Trust in Engineering Teams Ideal Number of Direct Reports Overriding a People Leader’s Decision From Misperception to Promotion Perception vs Perspective Setting Goals From Engineer to Manager Getting Delegation Right Interviewing Your Future Boss Celebrating Our Book in Iceland Operational Skills Needed On Writing Software Engineering Handbook Charlie Munger Quotes Working with Dependencies From Las Vegas to Canyons Navigating Layoffs Handling Competitive Dynamics A Weekend Getaway to Malta Engineering Health Essentials Should Dev Managers Code? Confronting the Life on Pause Winning Eleven Kindness is A Choice Bireysel Katılımcılar ve Yöneticiler Leading from Where You Are The Subtle Art of Listening Coding in Leadership The Power of Consistency The Making of a Leader The Path to Leadership Embracing TikTok Talent Sourcing Journey Leading Self Managing Teams Cracking Coding Bottlenecks
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.