Skip to content

Instantly share code, notes, and snippets.

@gwing33 gwing33/ReverseSpeeds.js
Last active Jan 1, 2016

Embed
What would you like to do?
Testing which Reverse String methods are faster... run it here: http://jsperf.com/reverse-speeds/2
// Run tests
function run_test(func) {
var j, s = 'asdfasdfasdf', name = func.name;
console.time(name);
for(j = 0; j <= 10000; j++) {
func(s);
}
console.timeEnd(name);
}
// split join reverse
function reverse_split_join(s) {
return s.split('').reverse().join('');
}
// For Negative Concat
function reverse_for_neg_concat(s) {
var reverse = '';
for(i = s.length-1; i >= 0; i--) {
reverse += s[i];
}
return reverse;
}
// For Negative join
function reverse_for_neg_join(s) {
var reverse = [];
for(i = s.length-1; i >= 0; i--) {
reverse.push(s[i]);
}
return reverse.join('');
}
// For Positive Concat
function reverse_for_pos_concat(s) {
var reverse = '', _ref = s.length - 1;
for(i = 0; i <= _ref; i++) {
reverse += value[_ref - i];
}
return reverse;
}
// For Positive Join
function reverse_for_pos_join(s) {
var reverse = [], _ref = s.length - 1;
for(i = 0; i <= _ref; i++) {
reverse.push(value[_ref - i]);
}
return reverse;
}
// While Negative Concat
function reverse_while_neg_concat(s) {
var reverse = '', _ref = s.length-1;
i = _ref;
while(i >= 0) {
reverse += s[i];
i--;
}
return reverse;
}
// While Negative Join
function reverse_while_neg_join(s) {
var reverse = [], _ref = s.length-1;
i = _ref;
while(i >= 0) {
reverse.push(s[i]);
i--;
}
return reverse.join('');
}
// While Positive Concat
function reverse_while_pos_concat(s) {
var reverse = [], i = 0;
while(i <= s.length-1) {
reverse += s[i];
i++;
}
return reverse;
}
// While Positive Join
function reverse_while_pos_join(s) {
var reverse = [], i = 0;
while(i <= s.length-1) {
reverse.push(s[i]);
i++;
}
return reverse.join('');
}
run_test(reverse_split_join);
run_test(reverse_for_neg_concat);
run_test(reverse_for_neg_join);
run_test(reverse_for_pos_concat);
run_test(reverse_for_pos_join);
run_test(reverse_while_neg_concat);
run_test(reverse_while_neg_join);
run_test(reverse_while_pos_concat);
run_test(reverse_while_pos_join);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.