Test str2ab

Benchmark created by Sam Dutton on


Description

Explain if worth getting str.length to variable at start of function when converting a String to ArrayBuffer.

Setup

function str2ab(str) {
        var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
        var bufView = new Uint16Array(buf);
        for (var i=0; i<str.length; i++) {
          bufView[i] = str.charCodeAt(i);
        }
        return buf;
      }
    
    function str2abWithVariable(str) {
        var l = str.length;
        var buf = new ArrayBuffer(l*2); // 2 bytes for each char
        var bufView = new Uint16Array(buf);
        for (var i=0; i<l; i++) {
          bufView[i] = str.charCodeAt(i);
        }
        return buf;
      }
    
    var veryLongStr = "ECMAScript [ECMA-262] has traditionally been used in contexts where there is no access to binary data. Where binary data has needed to be manipulated, it is often stored as a String and accessed using charCodeAt(), or stored as an Array with conversion to and from base64 for transmission. Both of these methods are slow and error-prone. For example, reading binary data as 32-bit integers requires manual conversion of 4 source bytes to and from the target type. Reading floating-point data is even more expensive. As web applications gain access to new functionality, working with binary data has become a much-demanded feature. Current specifications such as the File API [FILEAPI] and Web Sockets [WEBSOCKETS] would benefit from being able to read and write binary data directly in its native form. Specifications such as WebGL [WEBGL] require this functionality to meet acceptable performance characteristics. This specification defines a minimal set of functionality for accessing binary data from ECMAScript.";

Test runner

Ready to run.

Testing in
TestOps/sec
Without variable
var result = str2ab(veryLongStr);
ready
With variable
var result = str2abWithVariable(veryLongStr);
ready

Revisions

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

  • Revision 1: published by Sam Dutton on