Skip to content

Commit f84b0ba

Browse files
committed
Performance: improve .trim performance for large strings contains lots of whitespaces
The old implementation took O(N^2) time to trim the string when multiple adjacent spaces were present. For instance, consider the string "A B" (10 spaces between A and B). Then old regexp /[\s]+$/ would take 10 steps until it realizes the regexp does not match at position 1. Then it would try to match the regexp at position 2, and it would take 9 steps. Then 8 steps for position 3, ... so it would take 10*10/2 steps until it figures out the regexp does not match. See jquery/jquery#5068 The new approach is to require "non-whitespace" char before the whitespace run, so it spends just one step for each space in the string.
1 parent 8d9efb6 commit f84b0ba

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/jquery/core.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ var findProp,
1515
rattrHashTest = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/,
1616
rattrHashGlob = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/g,
1717

18-
// Support: Android <=4.0 only
19-
// Make sure we trim BOM and NBSP
20-
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
18+
// Require that the "whitespace run" starts from a non-whitespace
19+
// to avoid O(N^2) behavior when the engine would try matching "\s+$" at each space position.
20+
rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;
2121

2222
migratePatchFunc( jQuery.fn, "init", function( arg1 ) {
2323
var args = Array.prototype.slice.call( arguments );
@@ -109,7 +109,7 @@ if ( jQueryVersionSince( "3.1.1" ) ) {
109109
migratePatchAndWarnFunc( jQuery, "trim", function( text ) {
110110
return text == null ?
111111
"" :
112-
( text + "" ).replace( rtrim, "" );
112+
( text + "" ).replace( rtrim, "$1" );
113113
}, "trim",
114114
"jQuery.trim is deprecated; use String.prototype.trim" );
115115
}

0 commit comments

Comments
 (0)