Base Conversion Comparison

JavaScript performance comparison

Test case created by Josh Goodwin

Preparation code

<script>
  var num = "2047";
 
  function recursiveRebase(num, base) {
        return num < base ? num.toString() : recursiveRebase(Math.floor(num/base), base) + (num % base).toString();
  }
  function rebase(n, from, to) {
      return parseInt(n, from || 10).toString(to);
  }
  function getValueOfDigit(digit, alphabet) {
      var pos = alphabet.indexOf(digit);
      return pos;
  }
  function elenzil(src, srcAlphabet, dstAlphabet) {
      var srcBase = srcAlphabet.length;
      var dstBase = dstAlphabet.length;
 
      var wet = src;
      var val = 0;
      var mlt = 1;
 
      while (wet.length > 0) {
          var digit = wet.charAt(wet.length - 1);
          val += mlt * getValueOfDigit(digit, srcAlphabet);
          wet = wet.substring(0, wet.length - 1);
          mlt *= srcBase;
      }
 
      wet = val;
      var ret = "";
 
      while (wet >= dstBase) {
          var digitVal = wet % dstBase;
          var digit = dstAlphabet.charAt(digitVal);
          ret = digit + ret;
          wet /= dstBase;
      }
 
      var digit = dstAlphabet.charAt(wet);
      ret = digit + ret;
 
      return ret;
  }
</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
Native
num.toString(2);
pending…
elenzil
elenzil(num, "0123456789", "01")
pending…
native - arbitrary base
rebase(num, 10, 2)
pending…
recursive rebase
recursiveRebase(num,2)
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment