效果:typeof vs instanceof

时间:2018-05-03 14:31:47

标签: javascript performance instanceof typeof

我想知道typeofinstanceof中的哪一个更高效,所以我把以下小事整理在一起:

let TIMES = 1000 * 1000 * 100

console.time("(() => { }) instanceof Function")
for (let i = 0; i < TIMES; i++)
  (() => { }) instanceof Function
console.timeEnd("(() => { }) instanceof Function")

console.time("(async () => { }) instanceof Function")
for (let i = 0; i < TIMES; i++)
  (async () => { }) instanceof Function
console.timeEnd("(async () => { }) instanceof Function")

console.time("(function () { }) instanceof Function")
for (let i = 0; i < TIMES; i++)
  (function () { }) instanceof Function
console.timeEnd("(function () { }) instanceof Function")

console.time("(async function () { }) instanceof Function")
for (let i = 0; i < TIMES; i++)
  (async function () { }) instanceof Function
console.timeEnd("(async function () { }) instanceof Function")

console.time("typeof (() => { }) === 'function'")
for (let i = 0; i < TIMES; i++)
  typeof (() => { }) === 'function'
console.timeEnd("typeof (() => { }) === 'function'")

console.time("typeof (async () => { }) === 'function'")
for (let i = 0; i < TIMES; i++)
  typeof (async () => { }) === 'function'
console.timeEnd("typeof (async () => { }) === 'function'")

console.time("typeof (function () { }) === 'function'")
for (let i = 0; i < TIMES; i++)
  typeof (function () { }) === 'function'
console.timeEnd("typeof (function () { }) === 'function'")

console.time("typeof (async function () { }) === 'function'")
for (let i = 0; i < TIMES; i++)
  typeof (async function () { }) === 'function'
console.timeEnd("typeof (async function () { }) === 'function'")

从Chrome 66的控制台获得了超酷的结果:

(() => { }) instanceof Function: 1789.844970703125ms
(async () => { }) instanceof Function: 2229.64208984375ms
(function () { }) instanceof Function: 1954.09716796875ms
(async function () { }) instanceof Function: 2279.995849609375ms
typeof (() => { }) === 'function': 412.8701171875ms
typeof (async () => { }) === 'function': 413.337890625ms
typeof (function () { }) === 'function': 413.387939453125ms
typeof (async function () { }) === 'function': 412.910888671875ms

Firefox 59永远运行该XD

我没有足够的耐心等待它并使TIMES减少十倍:

let TIMES = 1000 * 1000 * 10

有了这个,我从Firefox 59的控制台得到了以下内容:

(() => { }) instanceof Function: 5490ms
(async () => { }) instanceof Function: 6884ms
(function () { }) instanceof Function: 5408ms
(async function () { }) instanceof Function: 6938ms
typeof (() => { }) === 'function': 1916ms
typeof (async () => { }) === 'function': 1998ms
typeof (function () { }) === 'function': 1976ms
typeof (async function () { }) === 'function': 1972ms

两个结果集都显示typeofinstanceof快得多,事实上其他几个人也在Which is best to use: typeof or instanceof?中提到过。

我的问题是“你呢”?

1 个答案:

答案 0 :(得分:0)

正如您还预测并展示了来自SO的其他链接,typeof会更快(jsperf:https://jsperf.com/instanceof-vs-typeof/5),这是有道理的,因为typeof将返回其中一个内置类型(对象,未定义和基元),同时您可以控制instanceof操作数的右侧。这意味着instanceof运算符应检查原型链,并查看右侧是否已用作构造函数 。这自然是更多的工作。