Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions benchmark/util/style-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,22 @@ const common = require('../common.js');
const { styleText } = require('node:util');
const assert = require('node:assert');

// 1000 distinct hex colors to exercise the cache under high-miss conditions.
// Spread evenly across hue space so colors are valid and maximally varied.
const kHexColorCount = 1000;
const toHex = (n) => n.toString(16).padStart(2, '0');
const hexColors = Array.from({ length: kHexColorCount }, (_, i) => {
const r = (i * 37) & 0xff;
const g = (i * 73) & 0xff;
const b = (i * 137) & 0xff;
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
});

const bench = common.createBenchmark(main, {
messageType: ['string', 'number', 'boolean', 'invalid'],
format: ['red', 'italic', 'invalid', '#ff0000'],
// '#rotating' cycles through kHexColorCount distinct colors to simulate
// the high-miss-rate / large-cache scenario (e.g. user-randomised colors).
format: ['red', 'italic', 'invalid', '#ff0000', '#rotating'],
validateStream: [1, 0],
n: [1e3],
});
Expand All @@ -31,9 +44,10 @@ function main({ messageType, format, validateStream, n }) {

bench.start();
for (let i = 0; i < n; i++) {
const fmt = format === '#rotating' ? hexColors[i % kHexColorCount] : format;
let colored = '';
try {
colored = styleText(format, str, { validateStream });
colored = styleText(fmt, str, { validateStream });
assert.ok(colored); // Attempt to avoid dead-code elimination
} catch {
// eslint-disable no-empty
Expand Down
71 changes: 49 additions & 22 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,11 @@ const kEscapeEnd = 'm';
const kDimCode = 2;
const kBoldCode = 1;

// Close sequence for 24-bit foreground colors (reset to default foreground)
const kHexCloseSeq = kEscape + '39' + kEscapeEnd;

let styleCache;
const hexStyleCache = { __proto__: null };
Copy link
Copy Markdown
Member

@Renegade334 Renegade334 Apr 29, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I note the benchmarks are all repeating the same lookup – I imagine that using a plain object as the map here could end up deoptimising if the cache miss rate is high, eg. colours being randomised by the user? Appreciate this is probably quite niche in reality, but might be worth a benchmark case to see how something like a SafeMap would compare.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There aren’t major differences.

Benchmark
util/style-text.js n=1000 validateStream=0 format='#ff0000' messageType='boolean'                  -1.31 %       ±3.83%  ±5.10%  ±6.64%
util/style-text.js n=1000 validateStream=0 format='#ff0000' messageType='invalid'                  -4.67 %       ±7.12%  ±9.54% ±12.55%
util/style-text.js n=1000 validateStream=0 format='#ff0000' messageType='number'                   -0.30 %       ±2.97%  ±3.95%  ±5.15%
util/style-text.js n=1000 validateStream=0 format='#ff0000' messageType='string'             *      3.74 %       ±3.70%  ±4.94%  ±6.44%
util/style-text.js n=1000 validateStream=0 format='#rotating' messageType='boolean'                -1.08 %       ±3.55%  ±4.72%  ±6.15%
util/style-text.js n=1000 validateStream=0 format='#rotating' messageType='invalid'                -4.76 %       ±7.76% ±10.39% ±13.66%
util/style-text.js n=1000 validateStream=0 format='#rotating' messageType='number'                 -0.09 %       ±3.19%  ±4.25%  ±5.54%
util/style-text.js n=1000 validateStream=0 format='#rotating' messageType='string'                  0.74 %       ±4.17%  ±5.55%  ±7.22%
util/style-text.js n=1000 validateStream=0 format='invalid' messageType='boolean'                   0.72 %       ±6.24%  ±8.33% ±10.89%
util/style-text.js n=1000 validateStream=0 format='invalid' messageType='invalid'                  -1.52 %       ±3.46%  ±4.60%  ±6.00%
util/style-text.js n=1000 validateStream=0 format='invalid' messageType='number'                    0.46 %       ±3.20%  ±4.27%  ±5.56%
util/style-text.js n=1000 validateStream=0 format='invalid' messageType='string'                    1.16 %       ±3.10%  ±4.13%  ±5.38%
util/style-text.js n=1000 validateStream=0 format='italic' messageType='boolean'                   -1.15 %       ±4.42%  ±5.93%  ±7.79%
util/style-text.js n=1000 validateStream=0 format='italic' messageType='invalid'                   -3.32 %       ±3.57%  ±4.75%  ±6.18%
util/style-text.js n=1000 validateStream=0 format='italic' messageType='number'                     1.35 %       ±3.67%  ±4.88%  ±6.35%
util/style-text.js n=1000 validateStream=0 format='italic' messageType='string'                    -1.02 %       ±4.64%  ±6.18%  ±8.04%
util/style-text.js n=1000 validateStream=0 format='red' messageType='boolean'                      -2.72 %       ±3.47%  ±4.61%  ±6.01%
util/style-text.js n=1000 validateStream=0 format='red' messageType='invalid'                      -1.47 %       ±3.57%  ±4.76%  ±6.20%
util/style-text.js n=1000 validateStream=0 format='red' messageType='number'                       -1.55 %       ±2.97%  ±3.96%  ±5.15%
util/style-text.js n=1000 validateStream=0 format='red' messageType='string'                       -0.42 %       ±4.55%  ±6.05%  ±7.88%
util/style-text.js n=1000 validateStream=1 format='#ff0000' messageType='boolean'                   0.65 %       ±5.41%  ±7.21%  ±9.42%
util/style-text.js n=1000 validateStream=1 format='#ff0000' messageType='invalid'            *     -3.55 %       ±2.88%  ±3.83%  ±4.99%
util/style-text.js n=1000 validateStream=1 format='#ff0000' messageType='number'                   -1.31 %       ±3.15%  ±4.20%  ±5.48%
util/style-text.js n=1000 validateStream=1 format='#ff0000' messageType='string'                    3.73 %       ±4.20%  ±5.59%  ±7.29%
util/style-text.js n=1000 validateStream=1 format='#rotating' messageType='boolean'                -1.73 %       ±4.42%  ±5.89%  ±7.70%
util/style-text.js n=1000 validateStream=1 format='#rotating' messageType='invalid'                -2.71 %       ±4.63%  ±6.17%  ±8.03%
util/style-text.js n=1000 validateStream=1 format='#rotating' messageType='number'                 -0.79 %       ±4.14%  ±5.52%  ±7.21%
util/style-text.js n=1000 validateStream=1 format='#rotating' messageType='string'                 -0.28 %       ±3.44%  ±4.58%  ±5.96%
util/style-text.js n=1000 validateStream=1 format='invalid' messageType='boolean'                   0.29 %       ±5.79%  ±7.70% ±10.02%
util/style-text.js n=1000 validateStream=1 format='invalid' messageType='invalid'                  -3.20 %       ±3.51%  ±4.67%  ±6.08%
util/style-text.js n=1000 validateStream=1 format='invalid' messageType='number'                   -1.35 %       ±2.60%  ±3.46%  ±4.50%
util/style-text.js n=1000 validateStream=1 format='invalid' messageType='string'                    1.61 %       ±2.64%  ±3.51%  ±4.58%
util/style-text.js n=1000 validateStream=1 format='italic' messageType='boolean'                    0.52 %       ±4.47%  ±5.95%  ±7.76%
util/style-text.js n=1000 validateStream=1 format='italic' messageType='invalid'                    2.16 %       ±6.08%  ±8.14% ±10.70%
util/style-text.js n=1000 validateStream=1 format='italic' messageType='number'                    -0.13 %       ±3.02%  ±4.01%  ±5.22%
util/style-text.js n=1000 validateStream=1 format='italic' messageType='string'                     0.73 %       ±3.93%  ±5.24%  ±6.83%
util/style-text.js n=1000 validateStream=1 format='red' messageType='boolean'                      -0.30 %       ±3.44%  ±4.59%  ±5.98%
util/style-text.js n=1000 validateStream=1 format='red' messageType='invalid'                      -0.79 %       ±4.18%  ±5.57%  ±7.25%
util/style-text.js n=1000 validateStream=1 format='red' messageType='number'                       -1.35 %       ±3.39%  ±4.51%  ±5.87%
util/style-text.js n=1000 validateStream=1 format='red' messageType='string'                        1.11 %       ±3.21%  ±4.27%  ±5.57%

Be aware that when doing many comparisons the risk of a false-positive
result increases. In this case, there are 40 comparisons, you can thus
expect the following amount of false-positive results:
2.00 false positives, when considering a   5% risk acceptance (*, **, ***),
0.40 false positives, when considering a   1% risk acceptance (**, ***),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should prefer SafeMap when we can


function getStyleCache() {
if (styleCache === undefined) {
Expand All @@ -137,6 +141,25 @@ function getStyleCache() {
return styleCache;
}

/**
* Returns the cached ANSI escape sequences for a hex color.
* Computes and caches on first use to avoid repeated Buffer allocations.
* @param {string} hex A valid hex color string (#RGB or #RRGGBB)
* @returns {{openSeq: string, closeSeq: string}}
*/
function getHexStyle(hex) {
const cached = hexStyleCache[hex];
if (cached !== undefined) return cached;
const { 0: r, 1: g, 2: b } = hexToRgb(hex);
const style = {
__proto__: null,
openSeq: kEscape + rgbToAnsi24Bit(r, g, b) + kEscapeEnd,
closeSeq: kHexCloseSeq,
};
hexStyleCache[hex] = style;
return style;
}

function replaceCloseCode(str, closeSeq, openSeq, keepClose) {
const closeLen = closeSeq.length;
let index = str.indexOf(closeSeq);
Expand All @@ -163,15 +186,6 @@ function replaceCloseCode(str, closeSeq, openSeq, keepClose) {
// Matches #RGB or #RRGGBB
const hexColorRegExp = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

/**
* Validates whether a string is a valid hex color code.
* @param {string} hex The hex string to validate (e.g., '#fff' or '#ffffff')
* @returns {boolean} True if valid hex color, false otherwise
*/
function isValidHexColor(hex) {
return typeof hex === 'string' && RegExpPrototypeExec(hexColorRegExp, hex) !== null;
}

/**
* Parses a hex color string into RGB components.
* Supports both 3-digit (#RGB) and 6-digit (#RRGGBB) formats.
Expand Down Expand Up @@ -225,6 +239,17 @@ function styleText(format, text, options) {
const processed = replaceCloseCode(text, style.closeSeq, style.openSeq, style.keepClose);
return style.openSeq + processed + style.closeSeq;
}

if (format[0] === '#') {
let hexStyle = hexStyleCache[format];
if (hexStyle === undefined && RegExpPrototypeExec(hexColorRegExp, format) !== null) {
hexStyle = getHexStyle(format);
}
if (hexStyle !== undefined) {
const processed = replaceCloseCode(text, hexStyle.closeSeq, hexStyle.openSeq, false);
return hexStyle.openSeq + processed + hexStyle.closeSeq;
}
}
}

validateString(text, 'text');
Expand Down Expand Up @@ -255,24 +280,26 @@ function styleText(format, text, options) {
for (const key of formatArray) {
if (key === 'none') continue;

if (isValidHexColor(key)) {
if (skipColorize) continue;
const { 0: r, 1: g, 2: b } = hexToRgb(key);
const openSeq = kEscape + rgbToAnsi24Bit(r, g, b) + kEscapeEnd;
const closeSeq = kEscape + '39' + kEscapeEnd;
openCodes += openSeq;
closeCodes = closeSeq + closeCodes;
processedText = replaceCloseCode(processedText, closeSeq, openSeq, false);
if (typeof key === 'string' && key[0] === '#') {
let hexStyle = hexStyleCache[key];
if (hexStyle === undefined) {
if (RegExpPrototypeExec(hexColorRegExp, key) === null) {
throw new ERR_INVALID_ARG_VALUE('format', key,
'must be a valid hex color (#RGB or #RRGGBB)');
}
if (skipColorize) continue;
hexStyle = getHexStyle(key);
} else if (skipColorize) {
continue;
}
openCodes += hexStyle.openSeq;
closeCodes = hexStyle.closeSeq + closeCodes;
processedText = replaceCloseCode(processedText, hexStyle.closeSeq, hexStyle.openSeq, false);
continue;
}

const style = cache[key];
if (style === undefined) {
// Check if it looks like an invalid hex color (starts with #)
if (typeof key === 'string' && key[0] === '#') {
throw new ERR_INVALID_ARG_VALUE('format', key,
'must be a valid hex color (#RGB or #RRGGBB)');
}
validateOneOf(key, 'format', ObjectGetOwnPropertyNames(inspect.colors));
}
openCodes += style.openSeq;
Expand Down
Loading