🌐 AI搜索 & 代理 主页
Skip to content

Commit 09bb467

Browse files
committed
Deprecated: improve .trim for strings containing 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. 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 0f6c3d9 commit 09bb467

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/deprecated.js

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,22 @@ define( [
66
"./var/isFunction",
77
"./var/isWindow",
88
"./var/slice",
9+
"./deprecated/support",
910

1011
"./deprecated/ajax-event-alias",
1112
"./deprecated/event"
12-
], function( jQuery, nodeName, camelCase, toType, isFunction, isWindow, slice ) {
13+
], function( jQuery, nodeName, camelCase, toType, isFunction, isWindow, slice, support ) {
1314

1415
"use strict";
1516

1617
// Support: Android <=4.0 only
1718
// Make sure we trim BOM and NBSP
18-
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
19+
// Require that the "whitespace run" starts from a non-whitespace
20+
// to avoid O(N^2) behavior when the engine would try matching "\s$" at each space position.
21+
// It is important that non-whitespace char is mandatory for regexp performance reasons,
22+
// however, it does not break correctness since whitespace-only string will be trimmed by ltrim above.
23+
var ltrim = /^[\s\uFEFF\xA0]+/,
24+
rtrim = /([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/;
1925

2026
// Bind a function to a context, optionally partially applying any
2127
// arguments.
@@ -80,8 +86,11 @@ jQuery.isNumeric = function( obj ) {
8086
};
8187

8288
jQuery.trim = function( text ) {
83-
return text == null ?
84-
"" :
85-
( text + "" ).replace( rtrim, "" );
89+
if ( text == null ) {
90+
return "";
91+
}
92+
return support.trim ?
93+
( text + "" ).trim() :
94+
( text + "" ).replace( ltrim, "" ).replace( rtrim, "$1" );
8695
};
8796
} );

src/deprecated/support.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
define( [
2+
"../var/support"
3+
], function( support ) {
4+
5+
"use strict";
6+
7+
support.trim = "".trim && "_" === " \uFEFF\xA0_\uFEFF\xA0 ".trim();
8+
9+
return support;
10+
11+
} );

0 commit comments

Comments
 (0)