Created
June 12, 2012 09:03
-
-
Save to/2916336 to your computer and use it in GitHub Desktop.
Bench, Method vs Grobal Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var text = new Array(500).join('-'); | |
| String.prototype.getLength = function(){ | |
| return this.length; | |
| } | |
| function getLength(str){ | |
| return str.length; | |
| } | |
| function empty(){ | |
| } | |
| function benchFunction(){ | |
| return getLength(text); | |
| } | |
| function benchMethod(){ | |
| return text.getLength(); | |
| } | |
| // ----[bench]----------------------------- | |
| var count = 1000000; | |
| function bench(name){ | |
| var start = Date.now(); | |
| var target = window[name]; | |
| for(var i=0 ; i<count ; i++) | |
| target(); | |
| console.log(name + ':' + (Date.now() - start) + 'ms'); | |
| } | |
| bench('empty'); | |
| bench('benchFunction'); | |
| bench('benchMethod'); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Chrome 19で、Function:27ms、 Method:2566ms。プロトタイプのメソッドにすると便利だけど速さが必要な所だとつらい。というかグローバルに置く関数がすごい速い。Firefox 13だと、Function:1127ms、Method:1358ms。差は無いけど…。