【发布时间】:2018-10-13 22:00:51
【问题描述】:
我想知道typeof 和instanceof 哪个性能更高,所以我把以下小东西放在一起:
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
两个结果集都显示typeof 比instanceof 快得多,Which is best to use: typeof or instanceof? 中也提到了其他几个人。
我的问题是“y tho”?
【问题讨论】:
-
但两者不可互换。在某些情况下,这两个运算符的用例会有所不同。见this post。
-
typeof只检查类型(一个简单的检查),instanceof也检查它是否属于一个超类(多个检查) -
我的猜测是因为VM中的变量默认有一个与之关联的类型标记,这比指针追踪到原型链更快。
标签: javascript performance instanceof typeof