js中循环性能对比

376 阅读1分钟

image.png

forEach的性能要比for循环的性能差。forEach循环接受两个参数,第一个是函数,其中函数的形参位置会默认传入三个值,分别是当前循环项,当前循环项的索引,循环的数组本身;同时forEach的第二个参数位置还能指定第一个函数参数执行时的this指向。forEach方法本身除了循环以外还做了许多其他处理,比如传参,判断类型,改变this指向等。

js实现forEach

Array.prototype._forEach = function (callback,context){
  if(typeof callback !== 'function') return 
  let self =this,
      len = this.length,
      i=0,
      context = context? context:window
  for(;i<len;i++){
    callback.call(context,this[i],i,this)
  }
}

for in 循环的性能很差,原因是它迭代的是整个对象中所有可枚举的属性(绝大部分私有属性和少部分共有属性,即原型链上的属性),所以递归整个原型链会很耗时同时还要判断是否可枚举。

image.png

问题:

  • 遍历顺序以数字优先
  • 无法遍历Symbol属性
  • 可以遍历到公有的可枚举方法

image.png

image.png

for of 循环的原理是按照数据类型本身实现的迭代器规范进行遍历的。

image.png

image.png

谈一下你对this的理解和应用场景

Function.prototype.call = function(context,...arg){
  let self = this,
      key = Symbol('KEY'),
      result
  context == null ? context = window:null
  !/^(object|function)$/i.text(typeof context)?context = Object(context):null
  context[key] = self
  result = context[key](...arg)
  delete context[key]
  return result
}
Function.prototype.bind = function(context,...arg1){
  let self = this
  return function(...arg2){
    this.call(context,...arg1,...arg2)
  }
}