Created
July 22, 2010 12:36
-
-
Save timwhitlock/485912 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* String reverse bench test script. | |
* Runs in javascript shell, see print() function | |
*/ | |
/** make a 1MB string */ | |
function bigString(){ | |
var s = ''; | |
for( var i = 0; i < 131072; i++ ){ | |
s += '12345678'; | |
} | |
return s; | |
} | |
/** make a 1KB string */ | |
function smallString(){ | |
var s = ''; | |
for( var i = 0; i < 128; i++ ){ | |
s += '12345678'; | |
} | |
return s; | |
} | |
/** simple timer to show results */ | |
var Timer = function(){ | |
this.t1 = (new Date).getTime(); | |
} | |
Timer.prototype.stop = function( s ){ | |
var t2 = (new Date).getTime(); | |
var t = t2 - this.t1; | |
print( '"'+s.slice(0,8)+' ... "' ); | |
print( ' > ' +t+ ' milliseconds'); | |
} | |
/** function 1 */ | |
function reverse_1( s ){ | |
var r = ''; | |
while( s ){ | |
r += s.substr(-1,1); | |
s = s.slice(0,-1); | |
} | |
return r; | |
} | |
/** function 2 */ | |
function reverse_2(){ | |
var r = '', i = 0, n = - s.length; | |
while( i > n ){ | |
r += s.substr(--i,1); | |
} | |
return r; | |
} | |
/** function 3 */ | |
function reverse_3(){ | |
var r = '', n = 0, len = s.length; | |
while( r.length < len ){ | |
r += s.substr(--n,1); | |
} | |
return r; | |
} | |
//var s = '12345678'; | |
//var s = smallString(); | |
var s = bigString(); | |
// run test 1 | |
var t = new Timer; | |
var r = reverse_1(s); | |
t.stop( r ); | |
// run test 2 | |
var t = new Timer; | |
var r = reverse_2(s); | |
t.stop( r ); | |
// run test 3 | |
var t = new Timer; | |
var r = reverse_3(s); | |
t.stop( r ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment