Reputation: 13994
So I'm looking for a way to generate all possible substrings from a larger String that start at index 0. So let's say we have
var a = "test";
Then I want to generate
"test", "tes", "te" and "t"
I imagine doing this with substring, substr or slice, and I tested them here: http://jsperf.com/loop-over-string
Now the slice method seems almost twice as fast as the other methods. Can anybody explain that? Or is there even faster ways to do this?
Upvotes: 4
Views: 2131
Reputation: 12420
In your benchmark slice
is faster because text
's length decreases each iteration.
If you take a look at substr
, substring
and slice
implementations in V8 you will realize that they use the same internal function %_SubString
. They only manipulate its parameters at a negligible cost.
String.prototype.slice
: https://github.com/v8/v8/blob/master/src/string.js#L567String.prototype.substring
: https://github.com/v8/v8/blob/master/src/string.js#L713String.prototype.substr
: https://github.com/v8/v8/blob/master/src/string.js#L748Upvotes: 4
Reputation: 214959
This appears to be faster:
substr = ""
for (var i = 0; i < length; i++) {
substr += text.charAt(i)
}
http://jsperf.com/loop-over-string/3
Upvotes: 1