Skip to content

Commit

Permalink
Improve performance of String.prototype.includes
Browse files Browse the repository at this point in the history
Summary:
Our current implmentation extracts every substring (of the source string) that
matches the length of the search string and check to see if any of them match.

This change just does one `std::search` of the search string in the source
string.

Reviewed By: avp

Differential Revision: D18359912

fbshipit-source-id: 24ce96f777aab2e0e6ab789f59c1be5030002dbc
  • Loading branch information
Kiwi137 authored and facebook-github-bot committed Nov 13, 2019
1 parent d275b00 commit ccf31a4
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/VM/JSLib/String.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2080,12 +2080,17 @@ CallResult<HermesValue> stringPrototypeIncludesOrStartsWith(
// than searchLen, the code unit at index k+j of S is the same as the code
// unit at index j of searchStr, return true; but if there is no such integer
// k, return false.
for (double k = start; k + searchLength <= len; ++k) {
if (S->sliceEquals(k, searchLength, *searchStr)) {
return HermesValue::encodeBoolValue(true);
}
}
return HermesValue::encodeBoolValue(false);
auto SView = StringPrimitive::createStringView(runtime, S);
auto searchStrView = StringPrimitive::createStringView(runtime, searchStr);
auto foundIter = std::search(
SView.begin() + start,
SView.end(),
searchStrView.begin(),
searchStrView.end());
// Note: searchStrView.empty check is needed in the special case that S is
// empty, searchStr is empty, and start = 0
return HermesValue::encodeBoolValue(
foundIter != SView.end() || searchStrView.empty());
}

/// Shared implementation of string.indexOf and string.lastIndexOf
Expand Down

0 comments on commit ccf31a4

Please sign in to comment.