Skip to content

Commit 6eff649

Browse files
committed
[JSC] Add fast path for String#split with /\r?\n/
https://bugs.webkit.org/show_bug.cgi?id=327627 Reviewed by Yusuke Suzuki. /\r?\n/ is the most common way to split text into lines. It is used by popular libraries such as terser, UglifyJS, PostCSS, @vue/compiler-sfc and globby. But only /\r\n?|\n/ was recognized as a specific pattern and took the vectorized path in regExpSplitFast. This patch adds SpecificPattern::OptionalCRThenLF for /\r?\n/. It shares the fast path with Newlines: search for the next LF, and include the preceding CR in the separator if there is one. The fast path does not populate the split cache, so we take it only when the subject is not cacheable. Otherwise repeated splits of the same atom string would become slower than the cached generic path. Baseline Patched string-split-regexp-optional-cr-then-lf 99.7721+-1.4003 ^ 54.8907+-0.8233 ^ definitely 1.8177x faster Tests: JSTests/microbenchmarks/string-split-regexp-optional-cr-then-lf.js JSTests/stress/string-split-regexp-optional-cr-then-lf.js * JSTests/microbenchmarks/string-split-regexp-optional-cr-then-lf.js: Added. (splitLines): * JSTests/stress/string-split-regexp-optional-cr-then-lf.js: Added. (shouldBe): (splitAndCaptureStatics): (compare): (split): (symbolSplit): (test): * Source/JavaScriptCore/runtime/RegExpPrototype.cpp: (JSC::regExpSplitFast): * Source/JavaScriptCore/runtime/StringPrototypeInlines.h: (JSC::tryTrimSpaces): * Source/JavaScriptCore/yarr/Yarr.h: * Source/JavaScriptCore/yarr/YarrPattern.cpp: (JSC::Yarr::YarrPatternConstructor::extractSpecificPattern): Canonical link: https://commits.webkit.org/323921@main
1 parent 381f81c commit 6eff649

6 files changed

Lines changed: 167 additions & 8 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function splitLines(text)
2+
{
3+
return text.split(/\r?\n/);
4+
}
5+
noInline(splitLines);
6+
7+
const lines = [];
8+
for (let i = 0; i < 200; ++i)
9+
lines.push("line " + i + " " + "x".repeat((i * 7) % 60));
10+
const lf = lines.join("\n");
11+
const crlf = lines.join("\r\n");
12+
13+
let count = 0;
14+
for (let i = 0; i < 1e4; ++i)
15+
count += splitLines(lf).length + splitLines(crlf).length;
16+
if (count !== 4e6)
17+
throw new Error("bad count: " + count);
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
function shouldBe(actual, expected, message) {
2+
if (actual !== expected)
3+
throw new Error(message + ": expected " + JSON.stringify(expected) + " but got " + JSON.stringify(actual));
4+
}
5+
6+
function splitAndCaptureStatics(regexp, input, limit) {
7+
/ZZZ/.exec("xxxZZZyyy");
8+
const result = input.split(regexp, limit);
9+
result.push(RegExp.input, RegExp.lastMatch, RegExp.leftContext, RegExp.rightContext, regexp.lastIndex);
10+
return result.join("|");
11+
}
12+
13+
function compare(source, flags, inputs, limits) {
14+
const regexp = new RegExp(source, flags);
15+
const reference = new RegExp("(?:" + source + ")", flags);
16+
regexp.lastIndex = reference.lastIndex = 3;
17+
for (const input of inputs) {
18+
for (const limit of limits) {
19+
const actual = splitAndCaptureStatics(regexp, input, limit);
20+
const expected = splitAndCaptureStatics(reference, input, limit);
21+
if (actual !== expected)
22+
throw new Error("/" + source + "/" + flags + " " + JSON.stringify(input) + " " + limit + ": expected " + JSON.stringify(expected) + " but got " + JSON.stringify(actual));
23+
}
24+
}
25+
}
26+
27+
const inputs = [""];
28+
for (let i = 0; inputs[i].length < 5; ++i) {
29+
for (const character of ["a", "\r", "\n"])
30+
inputs.push(inputs[i] + character);
31+
}
32+
const shortInputs = inputs.slice(0, 121);
33+
for (const input of inputs.slice(0, 40))
34+
inputs.push("\u3042" + input, input + "\u3042");
35+
for (const length of [7, 8, 15, 16, 17, 31, 32, 33, 63, 64, 65]) {
36+
for (const separator of ["\n", "\r\n", "\r", "\r\r\n", "\n\r"]) {
37+
for (const fill of ["x", "\u3042"])
38+
inputs.push(fill.repeat(length) + separator + fill.repeat(length) + separator);
39+
}
40+
}
41+
42+
compare("\\r?\\n", "", inputs, [undefined, 0, 1, 2, 5, -1]);
43+
44+
for (const flags of ["g", "ds"])
45+
compare("\\r?\\n", flags, shortInputs, [undefined, 2]);
46+
47+
for (const source of ["\\r\\n", "\\r??\\n", "\\r*\\n", "\\r+\\n", "\\r{0,2}\\n", "\\n?\\n", "a?\\n", "\\r?\\r", "\\r?a", "\\r?\\n?", "\\r?\\n*", "\\r?\\n+", "\\r?\\n{2}", "\\r?", "\\r?\\n\\n", "\\r?\\na", "\\r?\\n|a", "(\\r?\\n)", "^\\r?\\n", "\\r?\\n$"])
48+
compare(source, "", shortInputs, [undefined, 2]);
49+
50+
function split(input, limit) {
51+
return input.split(/\r?\n/, limit);
52+
}
53+
noInline(split);
54+
55+
function symbolSplit(input, limit) {
56+
return /\r?\n/[Symbol.split](input, limit);
57+
}
58+
noInline(symbolSplit);
59+
60+
function test(splitFunction, mixed, wide) {
61+
shouldBe(splitFunction(mixed).join("|"), "a|b|c\rd\r|e|\rf|", "mixed");
62+
shouldBe(RegExp.lastMatch, "\n", "lastMatch");
63+
shouldBe(RegExp.leftContext, "a\nb\r\nc\rd\r\r\ne\n\rf", "leftContext");
64+
shouldBe(RegExp.rightContext, "", "rightContext");
65+
66+
shouldBe(splitFunction(wide, 2).join("|"), "\u3042|\u3044", "wide");
67+
shouldBe(RegExp.lastMatch, "\n", "lastMatch with limit");
68+
shouldBe(RegExp.leftContext, "\u3042\r\n\u3044", "leftContext with limit");
69+
shouldBe(RegExp.rightContext, "\u3046\r", "rightContext with limit");
70+
}
71+
72+
const mixed = "a\nb\r\nc\rd\r\r\ne\n\rf\n";
73+
const wide = "\u3042\r\n\u3044\n\u3046\r";
74+
const nonAtomMixed = mixed.split("").join("");
75+
const nonAtomWide = wide.split("").join("");
76+
77+
for (let i = 0; i < testLoopCount; ++i) {
78+
const splitFunction = i & 1 ? split : symbolSplit;
79+
if (i & 2)
80+
test(splitFunction, mixed, wide);
81+
else
82+
test(splitFunction, nonAtomMixed, nonAtomWide);
83+
}

‎Source/JavaScriptCore/runtime/RegExpPrototype.cpp‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -925,8 +925,9 @@ JSCell* regExpSplitFast(JSGlobalObject* globalObject, RegExpObject* regexpObject
925925
return result;
926926
}
927927

928-
// Fast path for newline splitting pattern: \r\n?|\n
929-
if (regexp->specificPattern() == Yarr::SpecificPattern::Newlines) {
928+
// Fast path for newline splitting patterns: \r\n?|\n and \r?\n
929+
auto specificPattern = regexp->specificPattern();
930+
if (specificPattern == Yarr::SpecificPattern::Newlines || (specificPattern == Yarr::SpecificPattern::OptionalCRThenLF && !cacheable)) {
930931
JSArray* result = JSArray::tryCreate(vm, globalObject->arrayStructureForIndexingTypeDuringAllocation(ArrayWithContiguous), 1);
931932
if (!result) [[unlikely]] {
932933
throwOutOfMemoryError(globalObject, scope);
@@ -936,9 +937,9 @@ JSCell* regExpSplitFast(JSGlobalObject* globalObject, RegExpObject* regexpObject
936937
unsigned resultLength = 0;
937938
MatchResult lastMatchResult = MatchResult::failed();
938939

939-
auto processSplit = [&](auto span) {
940+
auto processSplit = [&](auto span, auto findSeparator) {
940941
while (position < inputSize && resultLength < limit) {
941-
auto newlinePos = WTF::findNextNewline(span, position);
942+
auto newlinePos = findSeparator(span, position);
942943
if (newlinePos.position == WTF::notFound)
943944
break;
944945

@@ -956,10 +957,27 @@ JSCell* regExpSplitFast(JSGlobalObject* globalObject, RegExpObject* regexpObject
956957
return ContinueSplit;
957958
};
958959

959-
if (input->is8Bit())
960-
processSplit(input->span8());
961-
else
962-
processSplit(input->span16());
960+
auto split = [&](auto findSeparator) {
961+
if (input->is8Bit())
962+
processSplit(input->span8(), findSeparator);
963+
else
964+
processSplit(input->span16(), findSeparator);
965+
};
966+
967+
if (specificPattern == Yarr::SpecificPattern::Newlines) {
968+
split([](auto span, size_t position) {
969+
return WTF::findNextNewline(span, position);
970+
});
971+
} else {
972+
split([](auto span, size_t position) -> WTF::NewlinePosition {
973+
size_t lineFeed = WTF::find(span, Latin1Character { '\n' }, position);
974+
if (lineFeed == WTF::notFound)
975+
return { };
976+
if (lineFeed > position && span[lineFeed - 1] == '\r')
977+
return { lineFeed - 1, 2 };
978+
return { lineFeed, 1 };
979+
});
980+
}
963981
RETURN_IF_EXCEPTION(scope, { });
964982

965983
if (lastMatchResult)

‎Source/JavaScriptCore/runtime/StringPrototypeInlines.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,6 +1237,7 @@ static ALWAYS_INLINE JSString* tryTrimSpaces(VM& vm, JSGlobalObject* globalObjec
12371237
case Yarr::SpecificPattern::LeadingSpacesStar:
12381238
case Yarr::SpecificPattern::Atom:
12391239
case Yarr::SpecificPattern::Newlines:
1240+
case Yarr::SpecificPattern::OptionalCRThenLF:
12401241
case Yarr::SpecificPattern::None:
12411242
break;
12421243
}

‎Source/JavaScriptCore/yarr/Yarr.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ enum class SpecificPattern : uint8_t {
8383
TrailingSpacesStar,
8484
TrailingSpacesPlus,
8585
Newlines,
86+
OptionalCRThenLF,
8687
};
8788

8889
enum class ExecutionMode : uint8_t {

‎Source/JavaScriptCore/yarr/YarrPattern.cpp‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2988,6 +2988,42 @@ class YarrPatternConstructor {
29882988
return false;
29892989
};
29902990

2991+
auto tryExtractOptionalCRThenLF = [&] -> bool {
2992+
// Detect patterns: \r?\n
2993+
// These patterns match LF (\n) and CRLF (\r\n)
2994+
2995+
auto& alternatives = m_pattern.m_body->m_alternatives;
2996+
if (alternatives.size() != 1)
2997+
return false;
2998+
2999+
auto* alternative = alternatives[0].get();
3000+
if (alternative->m_terms.size() != 2)
3001+
return false;
3002+
3003+
auto& term0 = alternative->m_terms[0];
3004+
if (term0.type != PatternTerm::Type::PatternCharacter)
3005+
return false;
3006+
if (term0.patternCharacter != '\r')
3007+
return false;
3008+
if (term0.quantityType != QuantifierType::Greedy)
3009+
return false;
3010+
if (term0.quantityMinCount || term0.quantityMaxCount != 1)
3011+
return false;
3012+
3013+
auto& term1 = alternative->m_terms[1];
3014+
if (term1.type != PatternTerm::Type::PatternCharacter)
3015+
return false;
3016+
if (term1.patternCharacter != '\n')
3017+
return false;
3018+
if (term1.quantityType != QuantifierType::FixedCount)
3019+
return false;
3020+
if (term1.quantityMinCount != 1 || term1.quantityMaxCount != 1)
3021+
return false;
3022+
3023+
m_pattern.m_specificPattern = SpecificPattern::OptionalCRThenLF;
3024+
return true;
3025+
};
3026+
29913027
if (tryExtractAtom())
29923028
return;
29933029

@@ -2999,6 +3035,9 @@ class YarrPatternConstructor {
29993035

30003036
if (tryExtractNewlines())
30013037
return;
3038+
3039+
if (tryExtractOptionalCRThenLF())
3040+
return;
30023041
}
30033042

30043043
ErrorCode LEGACY_NODELETE error() { return m_error; }

0 commit comments

Comments
 (0)