## 目標
有一個字符串?`var number = '100'`,我們要將它轉換成 Number 類型的 100。
目前有三個選項:+, parseInt, Number
請測試哪個方法更快。
## [](https://github.com/alsotang/node-lessons/tree/master/lesson10#知識點)知識點
1. 學習使用 benchmark 庫
2. 學習使用?[http://jsperf.com/](http://jsperf.com/)?分享你的 benchmark
## [](https://github.com/alsotang/node-lessons/tree/master/lesson10#課程內容)課程內容
首先去弄個 benchmark 庫,[https://github.com/bestiejs/benchmark.js](https://github.com/bestiejs/benchmark.js)?。
這個庫已經兩年沒有更新了,兩年前發了個 1.0.0 版本,直到現在。
用法也特別簡單,照著官網的 copy 下來就好。
我們先來實現這三個函數:
~~~
var int1 = function (str) {
return +str;
};
var int2 = function (str) {
return parseInt(str, 10);
};
var int3 = function (str) {
return Number(str);
};
~~~
然后照著官方的模板寫 benchmark suite:
~~~
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() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// 這里的 async 不是 mocha 測試那個 async 的意思,這個選項與它的時間計算有關,默認勾上就好了。
.run({ 'async': true });
~~~
直接運行:
[](https://box.kancloud.cn/2015-08-03_55bf0fa811879.png)
可以看到,parseInt 是最快的。
### [](https://github.com/alsotang/node-lessons/tree/master/lesson10#在線分享)在線分享
如果想要在線分享你的 js benchmark,用這個網站:[http://jsperf.com/](http://jsperf.com/)?。
比如我在上面測試?`Math.log`?的效率:
[http://jsperf.com/math-perf-alsotang](http://jsperf.com/math-perf-alsotang)
進入之后點擊那個?`Run tests`?按鈕,就可以在瀏覽器中看到它們的效率差異了,畢竟瀏覽器也是可以跑 js 的。
點擊這里:[http://jsperf.com/math-perf-alsotang/edit](http://jsperf.com/math-perf-alsotang/edit)?,就可以看到這個 benchmark 是怎么配置的,很簡單。
- 關于
- Lesson 0: 《搭建 Node.js 開發環境》
- Lesson 1: 《一個最簡單的 express 應用》
- Lesson 2: 《學習使用外部模塊》
- Lesson 3: 《使用 superagent 與 cheerio 完成簡單爬蟲》
- Lesson 4: 《使用 eventproxy 控制并發》
- Lesson 5: 《使用 async 控制并發》
- Lesson 6: 《測試用例:mocha,should,istanbul》
- Lesson 7: 《瀏覽器端測試:mocha,chai,phantomjs》
- Lesson 8: 《測試用例:supertest》
- Lesson 9: 《正則表達式》
- Lesson 10: 《benchmark 怎么寫》
- Lesson 11: 《作用域與閉包:this,var,(function () {})》
- Lesson 12: 《線上部署:heroku》
- Lesson 13: 《持續集成平臺:travis》
- Lesson 14: 《js 中的那些最佳實踐》
- Lesson 15: 《Mongodb 與 Mongoose 的使用》
- Lesson 16: 《cookie 與 session》
- Lesson 17: 《使用 promise 替代回調函數》