跳到主要内容

如何使用二进制提取RGB值

· 2 分钟阅读 · - · - ·

如何把颜色值提取从秒级优化到毫秒级,下面是使用正则表达式、字符串截取和二进制的性能对比。

function useRegex() {
console.time("使用正则表达式");
for (let color = 0; color <= 0xffffff; color++) {
const hexColor = color.toString(16).padStart(6, "0");
const match =
/(?<red>[\da-f]{2})(?<green>[\da-f]{2})(?<blue>[\da-f]{2})/i.exec(
hexColor
);
const { red, green, blue } = match.groups;
const r = parseInt(red, 16);
const g = parseInt(green, 16);
const b = parseInt(blue, 16);
}
console.timeEnd("使用正则表达式");
}

function useString() {
console.time("使用字符串截取");
for (let color = 0; color <= 0xffffff; color++) {
const hexColor = color.toString(16).padStart(6, "0");
const r = parseInt(hexColor.substring(0, 2), 16);
const g = parseInt(hexColor.substring(2, 4), 16);
const b = parseInt(hexColor.substring(4, 6), 16);
}
console.timeEnd("使用字符串截取");
}

function useBit() {
console.time("使用位操作");
for (let color = 0; color <= 0xffffff; color++) {
const r = (color & 0xff0000) >> 16;
const g = (color & 0xff00) >> 8;
const b = color & 0xff;
}
console.timeEnd("使用位操作");
}

console.log(`${0xffffff}个颜色值`);
useRegex();
useString();
useBit();
该内容为何方原创,转载请注明本页地址
https://iamhefang.cn/code/如何使用二进制提取RGB值