我想知道 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? 中提到的事实.我的问题是“你”?
最佳答案
正如您还预测并展示了来自 SO 的其他链接,typeof
会更快(jsperf : https://jsperf.com/instanceof-vs-typeof/5),这是有道理的,因为 typeof
当您控制 instanceof
的右侧时,将返回其中一种内置类型( 对象、未定义和原语 )操作数。这意味着 instanceof
运算符(operator)应检查 原型(prototype)链 并查看右侧是否已用作 构造函数 沿着某处。这自然是更多的工作。
关于javascript - 性能:typeof vs instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50157577/