Ryo Kuroyanagi

Posted on

# Benchmarking RGBA extraction from integer in JavaScript

I got a case I should convert integer RGBA value to RGBA object. I compared the speed of 2 methods. I got interesting results. So I report here!

# Case

An array of integers (e.g. 0xFF0000FF) is given and I need to extract RGBA parameters separately.

# Method 1. Uint8Array

Converts the color array to Uint8Array in bulk and gets by indexes.

``````const array = new Uint8Array(new Uint32Array(colors).buffer)
const len = colors.length
const results = []
for (let i = 0; i < len; i++) {
const a = array[4 * i]
const b = array[4 * i + 1]
const g = array[4 * i + 2]
const r = array[4 * i + 3]
results.push({
r, g, b, a
})
}
return results
``````

Simply uses a loop and apply bitmask and bit shifting.

``````const len = colors.length
const results = []
for (let i = 0; i < len; i++) {
const c = colors[i]
const r = (c & 0xFF000000) >> 24
const g = (c & 0x00FF0000) >> 16
const b = (c & 0x0000FF00) >> 8
const a = c & 0x000000FF
results.push({
r, g, b, a
})
}
``````

# Benchmarking results

I prepared 4 kinds of data.

• HD: 1280 x 720
• Full HD: 1920 x 1080
• 4K: 3840 x 2160
• 8K: 7680 x 4320

I measured in 2 platforms Node.js and Chrome browser. I ran the same process ten times. The result number is in milli seconds. In Node.js, the bitmask method always wins. However, in browser, Unit8Array method always wins!ðŸ˜‚ Furthermore, in Uint8Array method, Browser beats Node.js!!!

Node.js (14.16.0 on Windows 10)

HD 1501 556
full HD 3367 1379
4K 13706 4668
8K 71298 20553

Chrome browser (94.0.4606.81)