Willem Mulder
Willem Mulder

Reputation: 13994

JS: Fastest way to create all substrings starting at index 0

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

Answers (2)

Florent
Florent

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.

Upvotes: 4

georg
georg

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

Related Questions