前端之 —— node.js摸爬打滚之路(三)

学习使用 benchmark 库:

 

1、创建并进入ventor,执行以下命令安装benchmark库:

cnpm i -g benchmark

2、新建app.js文件,copy以下测试内容至app.js:

var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;

var int1 = function(str){
    return + str
}
var int2 = function(str){
    return parseInt(str)
}
var int3 = function(str){
    return Number(str)
}

var number = '100';

suite
.add('+', function() {
  int1(number);
})
.add('parseInt', function() {
  int2(number);
})
.add('Number', function () {
  int3(number);
})

.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete',function(event){
    console.log('Fastest is' + this.filter('fastest').map('name'))
})
.run({'async': true})

3、node执行app.js文件:

node app.js

得下图:

由图可知,执行了四次,次次结果不同,一点也不准  >_<  ,不过应该是计算量太小,误差过大导致,理论上是parseInt方法性能更优。

原文地址:https://www.cnblogs.com/geewonii/p/7307247.html