Created
December 2, 2015 00:28
-
-
Save mitsuru793/ed230c5d262d2c84dcfc to your computer and use it in GitHub Desktop.
callとapplyの違いを確かめてみる
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
| function Person(name) { | |
| this.name = name; | |
| } | |
| Person.prototype.hello = function(toName, greet) { | |
| console.log(this.name + ":" + toName + "さん!" + greet); | |
| } | |
| Person.prototype.helloTest = function(toName, greet) { | |
| this.name + ":" + toName + "さん!" + greet; | |
| } | |
| tanaka = new Person("田中"); | |
| suzuki = new Person("鈴木"); | |
| tanaka.hello("志保", "こんにちは"); // 田中:志保さん!こんにちは | |
| suzuki.hello("真弓", "おはよう"); // 鈴木:真弓さん!おはよう | |
| // tanakaインスタンスがhelloを実行しているのに、発言者が鈴木になっている | |
| // thisを第1引数のsuzukiに置き換えています。 | |
| // callとapplyの違いは、関数への引数を配列でまとめて渡すか、可変引数にして渡すかの違いです。 | |
| tanaka.hello.call(suzuki, "新人", "よろしくね"); // 鈴木:新人さん!よろしくね | |
| tanaka.hello.apply(suzuki, ["新人", "よろしくね"]); // 鈴木:新人さん!よろしくね | |
| // callとapplyを10万回ループさせて、処理速度を比較 | |
| // callの方がapplyより、3倍近く速かったです。 | |
| // 新しく配列オブジェクトを生成する必要ない分速いのかもしれません。 | |
| repeat = 100000; | |
| console.time('call'); | |
| for (var i = 0; i < repeat; i++) { | |
| tanaka.helloTest.call(suzuki, "新人", "よろしくね"); | |
| } | |
| console.timeEnd('call'); // call: 3ms | |
| console.time('apply'); | |
| for (var i = 0; i < repeat; i++) { | |
| tanaka.helloTest.apply(suzuki, ["新人", "よろしくね"]); | |
| } | |
| console.timeEnd('apply'); // apply: 8ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment