Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 734
Willem Mulder Avatar asked Sep 03 '25 01:09

Willem Mulder


1 Answers

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#L567
  • String.prototype.substring: https://github.com/v8/v8/blob/master/src/string.js#L713
  • String.prototype.substr: https://github.com/v8/v8/blob/master/src/string.js#L748
like image 170
Florent Avatar answered Sep 04 '25 15:09

Florent