Encode String

JavaScript performance comparison

Revision 3 of this test case created by Cong Liu

Preparation code

<script src="//github.com/ghostoy/js-binarypack/raw/master/dist/binarypack.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer lectus quam, adipiscing sit amet lobortis eu, lacinia ac lacus. Etiam luctus commodo enim, sit amet iaculis ante dictum in. Ut ut eros sed lacus eleifend pretium. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum vel elit neque. Etiam fringilla lobortis arcu et sollicitudin. Nulla convallis augue at sapien tempor scelerisque. Donec felis mi, tempor sit amet aliquet et, laoreet id elit. Nunc mollis, arcu sed laoreet fermentum, ligula urna fringilla enim, vel dictum massa massa vel nibh. Pellentesque vel mauris massa. Phasellus vulputate nisl sit amet velit bibendum ac commodo quam interdum. Quisque sed enim neque, vitae faucibus augue. Nulla iaculis arcu a ligula congue convallis. Suspendisse bibendum tincidunt elit quis luctus. Donec consequat viverra urna in lacinia. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc sit amet.";
   
    function encode_utf8(data) {
      if (data == '' || data == null) {
        return '';
      }
      var buffer = [];
      var pos = 0;
      for (var i = 0; i < data.length; i++) {
        var c = data.charCodeAt(i);
        if (c > 0x10000) {
          // 4 bytes
          buffer[pos++] = 0xF0 | ((c & 0x1C0000) >>> 18);
          buffer[pos++] = 0x80 | ((c & 0x3F000) >>> 12);
          buffer[pos++] = 0x80 | ((c & 0xFC0) >>> 6);
          buffer[pos++] = 0x80 | (c & 0x3F);
        } else if (c > 0x800) {
          // 3 bytes
          buffer[pos++] = 0xE0 | ((c & 0xF000) >>> 12);
          buffer[pos++] = 0x80 | ((c & 0xFC0) >>> 6);
          buffer[pos++] = 0x80 | (c & 0x3F);
        } else if (c > 0x80) {
          // 2 bytes
          buffer[pos++] = 0xC0 | ((c & 0x7C0) >>> 6);
          buffer[pos++] = 0x80 | (c & 0x3F);
        } else {
          // 1 byte
          buffer[pos++] = c;
        }
      }
      return new Uint8Array(buffer);
    }
};
</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
BinaryPack
var blob = BinaryPack.pack(input);
pending…
Blob
var blob = new Blob([input]);
pending…
ArrayBuffer
var ab = encode_utf8(input);
pending…
JSON
var json = JSON.stringify(input);
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:

0 comments

Add a comment