I'm working on a library specifically for Utilities. It will have functions that help you manipulate: Strings, Arrays, Numbers, Objects, and more. Performance is a main focus. While working on the repeat function for Strings (repeat a string n
number of times), I decided to test out how fast my current method:
Array(n + 1).join(string); // n = times to repeat; string = string to copy
is compared to just using a loop. It turns out, that while this is the shortest way to repeat a string, it is also the slowest. I do understand it is still fast. I mean, it is impossible for a human to do 200,000 things in 1 second but in comparison to loops it is slow.
What makes loops so fast? One loop I noticed that is particularly fast is the while loop which contain i--
:
var i = 10;
while (i--) {
// do stuff
}
I decided to use this method since it is the fastest. But I wanted to know why? What makes it so much faster than the other methods?
Here is my benchmark. The only browser where the while loop was slower than the for loop was in Opera. It was especially fast in Internet Explorer 10.