Reflect.applyとFunction.prototype.applyの速度を計測してみた
ESLintのprefer-reflect
というルールをONにした
最近、Node.js v6が出たのでバージョンアップがてら、ESLintのprefer-reflect
というルールをONにしました。
そして、既存のソースに早速ESLintをかけたところ・・・
警告ががが
既存のソースに早速ESLintをかけたところ func.call(obj, a)
みたいに書いている箇所で警告を受けました。
http://eslint.org/docs/rules/prefer-reflectによれば、下記の古いメソッドはReflect.xxxに置き換えられると。
Reflect.apply effectively deprecates Function.prototype.apply and Function.prototype.call
Reflect.deleteProperty effectively deprecates the delete keyword
Reflect.getOwnPropertyDescriptor effectively deprecates Object.getOwnPropertyDescriptor
Reflect.getPrototypeOf effectively deprecates Object.getPrototypeOf
Reflect.setPrototypeOf effectively deprecates Object.setPrototypeOf
Reflect.preventExtensions effectively deprecates Object.preventExtensions
Functionのcall
やapply
はReflect.apply
に書き換えなさいとのこと。
ESLintのルールに従い、素直に書き換えよう!とは思ったのですが、速度が激遅にならないかが気になりました。
そこで超ざっくり計測
console.time
にてざっくりと。
'use strict'; function log(i) { return String(i); } for (let n = 1; n <= 10; n++) { console.log(`------------${n}回目-----------`); console.time('Function.apply'); for (let i = 0; i < 100000; i++) { log.apply(log, [i]); } console.timeEnd('Function.apply'); console.time('Reflect.apply'); for (let i = 0; i < 100000; i++) { Reflect.apply(log, undefined, [i]); } console.timeEnd('Reflect.apply'); }
結果。
------------1回目----------- Function.apply: 13.736ms Reflect.apply: 11.770ms ------------2回目----------- Function.apply: 13.979ms Reflect.apply: 8.198ms ------------3回目----------- Function.apply: 10.134ms Reflect.apply: 9.899ms ------------4回目----------- Function.apply: 9.800ms Reflect.apply: 11.548ms ------------5回目----------- Function.apply: 11.939ms Reflect.apply: 7.979ms ------------6回目----------- Function.apply: 8.048ms Reflect.apply: 8.330ms ------------7回目----------- Function.apply: 11.209ms Reflect.apply: 12.215ms ------------8回目----------- Function.apply: 11.397ms Reflect.apply: 8.974ms ------------9回目----------- Function.apply: 9.948ms Reflect.apply: 10.000ms ------------10回目----------- Function.apply: 8.923ms Reflect.apply: 11.215ms
結論
遅いということはなさそうなので、安心して使えそう。