Last active
January 10, 2021 13:42
-
-
Save stebunovd/9f906632286310a7ad0ee8abf853d6b0 to your computer and use it in GitHub Desktop.
DOM manipulation vs. CSSOM manipulation: simple speed test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>DOM vs CSSOM manipulation: simple speed test</title> | |
<style type="text/css"> | |
div { | |
background-color: #ccc; | |
display: inline-block; | |
height: 10px; | |
width: 10px; | |
} | |
.active { | |
background-color: #f00; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="block0"></div> | |
<div id="block1"></div> | |
<div id="block2"></div> | |
<div id="block3"></div> | |
<div id="block4"></div> | |
<div id="block5"></div> | |
<div id="block6"></div> | |
<script> | |
var blocksCount = 7; | |
var iterations = 10 * 1e6; | |
var blockId; | |
var i; | |
var start; | |
/*********/ | |
console.log('Test 1: DOM manipulation, ' + iterations + ' iterations:'); | |
start = new Date(); | |
blockId = 0; | |
for (i = 0; i < iterations; i++) { | |
document.getElementById('block' + blockId).classList.remove('active'); | |
blockId = (blockId + 1) % blocksCount; | |
document.getElementById('block' + blockId).classList.add('active'); | |
} | |
console.log('Elapsed: ', new Date() - start + 'ms'); | |
/*********/ | |
console.log('Test 2: optimized DOM manipulation, ' + iterations + ' iterations:'); | |
var blocksCache = []; | |
start = new Date(); | |
for (blockId = 0; blockId < blocksCount; blockId++) { | |
blocksCache.push(document.getElementById('block' + blockId)); | |
} | |
blockId = 0; | |
for (i = 0; i < iterations; i++) { | |
blocksCache[blockId].classList.remove('active'); | |
blockId = (blockId + 1) % blocksCount; | |
blocksCache[blockId].classList.add('active'); | |
} | |
console.log('Elapsed: ', new Date() - start + 'ms'); | |
/*********/ | |
console.log('Test 3: CSSOM manipulation, ' + iterations + ' iterations:') | |
start = new Date(); | |
var cssRule = document.styleSheets[0].cssRules[1]; | |
blockId = 0; | |
for (i = 0; i < iterations; i++) { | |
cssRule.selectorText = '#block' + blockId; | |
blockId = (blockId + 1) % blocksCount; | |
} | |
console.log('Elapsed: ', new Date() - start + 'ms'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was curious if DOM manipulation is faster than CSSOM. Here are results on my machine, average after 5 tests in each browser: