Skip to content

Instantly share code, notes, and snippets.

@kawanet
Last active December 11, 2021 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kawanet/4676a1804bb463ea558017b063d4c286 to your computer and use it in GitHub Desktop.
Save kawanet/4676a1804bb463ea558017b063d4c286 to your computer and use it in GitHub Desktop.
drawPixel(output, pos, ...color) is slow
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>benchmark</title>
</head>
<body>
Open DevTools
<script>
setTimeout(function() {
"use strict"
const length = 100000000;
const output = new Uint8ClampedArray(length);
const color = [255, 255, 255];
function bench(name, fn) {
const date = Date.now();
fn();
console.log(name, "// => ", Date.now() - date, "ms");
}
bench("drawPixel(output, pos, ...color)", function() {
for (let pos = 0; pos < length; pos++) {
drawPixel(output, pos, ...color);
}
});
bench("drawPixel(output, pos, color[0], color[1], color[2])", function() {
for (let pos = 0; pos < length; pos++) {
drawPixel(output, pos, color[0], color[1], color[2]);
}
});
bench("drawColorFn(output, color)(pos)", function() {
const drawPixel = drawColorFn(output, color);
for (let pos = 0; pos < length; pos++) {
drawPixel(pos);
}
});
function drawPixel(output, pos, r, g, b) {
output[pos + 0] = r;
output[pos + 1] = g;
output[pos + 2] = b;
output[pos + 3] = 255;
}
function drawColorFn(output, c) {
const r = c[0];
const g = c[1];
const b = c[2];
return function(pos) {
output[pos + 0] = r;
output[pos + 1] = g;
output[pos + 2] = b;
output[pos + 3] = 255;
};
}
}, 1);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment