From 95cc2c97b5913309e283aa03131fbe7c72130215 Mon Sep 17 00:00:00 2001 From: Ivan Babak Date: Sun, 1 Jul 2018 19:47:55 -0700 Subject: [PATCH] fix(perf): shortcut getStringWidth for ASCII-only strings (#4776) (#4790) --- src/common/util.js | 8 ++++++++ src/doc/doc-printer.js | 6 +++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/common/util.js b/src/common/util.js index 4ec2f0e3..fece2904 100644 --- a/src/common/util.js +++ b/src/common/util.js @@ -6,6 +6,9 @@ const escapeStringRegexp = require("escape-string-regexp"); const getCjkRegex = require("cjk-regex"); const getUnicodeRegex = require("unicode-regex"); +// eslint-disable-next-line no-control-regex +const notAsciiRegex = /[^\x20-\x7F]/; + const cjkPattern = getCjkRegex().source; // http://spec.commonmark.org/0.25/#ascii-punctuation-character @@ -713,6 +716,11 @@ function getStringWidth(text) { return 0; } + // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` + if (!notAsciiRegex.test(text)) { + return text.length; + } + // emojis are considered 2-char width for consistency // see https://github.com/sindresorhus/string-width/issues/11 // for the reason why not implemented in `string-width` diff --git a/src/doc/doc-printer.js b/src/doc/doc-printer.js index cc3ecfe0..72e2be2f 100644 --- a/src/doc/doc-printer.js +++ b/src/doc/doc-printer.js @@ -1,6 +1,6 @@ "use strict"; -const util = require("../common/util"); +const { getStringWidth } = require("../common/util"); const { concat, fill, cursor } = require("./doc-builders"); /** @type {{[groupId: PropertyKey]: MODE}} */ @@ -130,7 +130,7 @@ function fits(next, restCommands, width, options, mustBeFlat) { const doc = x[2]; if (typeof doc === "string") { - width -= util.getStringWidth(doc); + width -= getStringWidth(doc); } else { switch (doc.type) { case "concat": @@ -224,7 +224,7 @@ function printDocToString(doc, options) { if (typeof doc === "string") { out.push(doc); - pos += util.getStringWidth(doc); + pos += getStringWidth(doc); } else { switch (doc.type) { case "cursor":