String of n character

JavaScript performance comparison

Test case created by Marcel Duran

Info

This is a comparison of various ways to build a string of n repeated character, like ********* or --------- or whatever character. There are threads related in JSLint Yahoo! groups (http://tech.groups.yahoo.com/group/jslintcom/message/614 and http://tech.groups.yahoo.com/group/jslintcom/message/1648)

Preparation code

<script>
  var cnt = 1000,
      char = '*';
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
new Array
var str = new Array(cnt + 1).join(char);
pending…
array literal joining empty string
var a = [],
    x, str;
for (x = 0; x < cnt; x += 1) {
 a[x] = char;
}
str = a.join('');
pending…
array literal joining char
var a = [],
    x, str;
for (x = 0; x <= cnt; x += 1) {
 a[x] = '';
}
str = a.join(char);
pending…
array literal .length property
var a = [],
    str;
a.length = cnt + 1;
str = a.join(char);
pending…
array literal joining empty string reverse loop
var a = [],
    x = cnt,
    str;
while (x--) {
 a[x] = char;
}
str = a.join('');
pending…
array literal joining char reverse loop
var a = [],
    x = cnt + 1,
    str;
while (x--) {
 a[x] = '';
}
str = a.join(char);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

Alexandre Morgaut commented :

Interesting to see that on Opera the "array literal .length property" method is the fastest with "new Array" in second position

Jason Miller commented :

I guess it figures that the simplest way is the slowest (new Array(x).join(c)). This just means people should be putting a bit more effort into their padding functions when writing new libraries.

Add a comment