Convert byte array to hex string

JavaScript performance comparison

Revision 7 of this test case created by Hermann Stamm-Wilbrandt

Info

Was only intended to be a oneline solution, but appears to outperform the other implementations by orders or magnitude ...

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var byteArrayData = [],
      i = 0;
    while (i < 10000) {
      byteArrayData.push(Math.floor(Math.random() * 255));
      i++;
    }
};

Benchmark.prototype.teardown = function() {
    byteArrayData = [];
};
</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
String length compare
var ret = "",
  i = 0,
  len = byteArrayData.length;
while (i < len) {
  var h = byteArrayData[i].toString(16);
  if (h.length < 2) {
    h = "0" + h;
  }
  ret += h;
  i++;
}
pending…
Byte value compare inline.
var ret = "",
  i = 0,
  len = byteArrayData.length;
while (i < len) {
  var a = byteArrayData[i];
  var h = (a < 10 ? "0" : "") + a.toString(16);
  ret += h;
  i++;
}
pending…
Byte value compare expanded
var ret = "",
  i = 0,
  len = byteArrayData.length;
while (i < len) {
  var a = byteArrayData[i];
  var h = a.toString(16);
  if (a < 10) {
    h = "0" + h;
  }
  ret += h;
  i++;
}
pending…
Byte value compare dupe
var ret = "",
  i = 0,
  len = byteArrayData.length;
while (i < len) {
  var a = byteArrayData[i],
    h;
  if (a < 10) {
    h = "0" + a.toString(16);
  } else {
    h = a.toString(16);
  }
  ret += h;
  i++;
}
pending…
recursive oneliner
// convert byte array to hex string
function _(a,  /* aux. var */ b) {
  if (b = a.shift()) { return ("0"+b.toString(16)).slice(b>=0x10) + _(a); }
}

var ret = _(byteArrayData);
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:

1 comment

Hermann Stamm-Wilbrandt commented :

New recursive oneliner test is wrong.

Vyacheslav Egorov pointed this out on twitter: ... with destructive shift only first iteration of the benchmarking loop after setup makes sense, the rest operate on empty array

Anyway, nice (destructive) byteArray2hexString() oneliner is left.

Comment form temporarily disabled.

Add a comment