首页 > this指针和闭包那个性能更好?

this指针和闭包那个性能更好?

在编程的时候经常会遇到this指针和闭包同时存在的问题。如下面的代码所示。
【1】使用这两种方法都能解决问题,但是那个性能会更好些。怎么分析?
【2】在使用第二种方法中,使用了bind改变了this指针后,是否仍相对于test函数形成闭包?

<script>
    function test() {
        var obj = {name: 1};
        window.setTimeout(function () {
            console.log(obj.name);
        }, 1000);
        window.setTimeout(function () {
            console.log(this.name);
        }.bind(obj), 1000);
    }
    test();
</script>

https://jsfiddle.net/hsfzxjy/xm46t186/

let obj = { name: 1 }

function func1 () {
    obj.name = 2
}

let func2 = function () {
    this.name = 2
}.bind(obj)

function test (func) {
    let i
    for (i = 0;i < 1000000; i++) func()
}

console.time('func1')
test(func1)
console.timeEnd('func1')

console.time('func2')
test(func2)
console.timeEnd('func2')

结果差异显著:


相关阅读:Why is bind slower than a closure?


一条直路,你要绕一下那肯定慢!


这个问题意义不大,JS不像Java,没有bytecode和stack machine定义,就是说,看实现;而且现代JS编译器都是inline caching的,对于过于简单的代码都很快做到hot path optimization,real world性能和前面那样简单的benchmarking,相去甚远。闭包在很多时候是非常方便和易懂的,该用就用。


必然是第一种性能好...原因是call,apply,bind这种绑定this的操作非常耗性能...


setTimeout可以传参数的,作为参数传过去,这样肯定比以上两种都快。
https://developer.mozilla.org...

let obj = { name: 1 }

function func1 () {
    obj.name = 2
}

let func2 = function () {
    this.name = 2
}.bind(obj)

let func3 = function (obj) {
        obj.name=2
}
function test (func) {
    let i
    for (i = 0;i < 1000000; i++) func()
}

function test1 (func,obj) {
    let i
    for (i = 0;i < 1000000; i++) func(obj)
}

console.time('func1')
test(func1)
console.timeEnd('func1')

console.time('func2')
test(func2)
console.timeEnd('func2')

console.time('func3')
test1(func3,obj)
console.timeEnd('func3')


200倍以上,果断不能用!


你在 node 里面跑跑试试,我在 6.3.1 里跑,高票答案的 func1 和 func2 调整顺序会有惊喜,至于为什么,自己去查把,不要人云亦云。

另外 Bind 并非不能用,看你用在哪。


闭包好一点,除非你用that保留this,不然this丢失了你分分钟都不能debug出来

【热门文章】
【热门文章】