DEV Community

Ryo Kuroyanagi
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
Enter fullscreen mode Exit fullscreen mode

Method 2. Bitmask

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
  })
}
Enter fullscreen mode Exit fullscreen mode

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)

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

Chrome browser (94.0.4606.81)

Uint8Array Bitmask
HD 546 851
full HD 939 1990
4K 3209 9157
8K 11872 42438

In the Uint8Array method, number of accessing array is larger. In the bitmask method, number of calculation is larger. Therefore, the reason can be calculation is faster in Node.js and accessing array is faster in Chrome browser. This is just my guess though ...

Top comments (0)