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?
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#L748If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With