Random String
JavaScript performance comparison
Preparation code
<script>
Benchmark.prototype.setup = function() {
function randomString1 (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
while (strLength--) {
result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
}
return result.join('');
}
function randomString2 (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'];
while (strLength--) {
result.push(charSet[Math.floor(Math.random() * charSet.length)]);
}
return result.join('');
}
function randomString3 (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
while (--strLength) {
result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
}
return result.join('');
}
function randomString4 (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
charSet = charSet.split();
while (--strLength) {
result.push(charSet[Math.floor(Math.random() * charSet.length)]);
}
return result.join('');
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
randomString1 |
|
pending… |
randomString2 |
|
pending… |
randomString3 |
|
pending… |
randomString4 |
|
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:
- Revision 1: published by Gajus
- Revision 2: published
2 comments
1 op instead of 2 wins
Nice stuff. Opera 12.10 test was run on Android 4.1.2 SGS2 in desktop mode.