最近一个需求,需要用浏览器读取图片在前端缩略显示并且根据文件信息排序。

最近jsperf挂了, V2还在开发不太好用, 现在这里存个档。

使用Benchmark.js测试性能

写一个小页面测试两种方法速度:

(function () {
  var suite = null;

  function readFile(file, method, deferred) {
    var fr = new FileReader();
    fr[method](file);
    fr.onloadend = function() {
      deferred.resolve();
    }
  }

  function runSuite(file) {
    suite = new Benchmark.Suite({
      name: 'FileReader perf'
    });

    suite
      .add('FileReader.readAsArrayBuffer', {
        defer: true,
        fn: function(deferred) {
          readFile(file, 'readAsArrayBuffer', deferred);
        }
      })
      .add('FileReader.readAsDataURL', {
        defer: true,
        fn: function(deferred) {
          readFile(file, 'readAsDataURL', deferred);
        }
      })
      .on('complete', function(evt) {
        console.log('completed');
        this.forEach(function(bench) {
          console.log('Bench: ', bench.name);
          console.log('Hz: ', bench.hz);
        });
      })
      .run();
  }

  function onFileChage(e) {
    var file = e.target.files[0];
    runSuite(file);
  }
  document.getElementById('fileinput').addEventListener('change', onFileChage);
})();

结果

在我的MBP上测试:

== Firefox 39.0 ==

"Bench: " "FileReader.readAsArrayBuffer"
"Hz: " 2852.075550774104
"Bench: " "FileReader.readAsDataURL"
"Hz: " 967.485735798381

== Chrome 43.0 ==

Bench:  FileReader.readAsArrayBuffer
Hz:  221.9625071172418
Bench:  FileReader.readAsDataURL
Hz:  206.2738933937363