gpt4 book ai didi

javascript - JS 模块模式 = 缓存/更好的性能?

转载 作者:行者123 更新时间:2023-11-30 13:12:29 25 4
gpt4 key购买 nike

我刚刚读了这篇文章http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/ .

在标题为“#4 添加缓存”的部分中,它说:

By forming a closure around the mixins we can cache the results of the initial definition run and the performance implications are outstanding.

我不明白它是如何工作的——在这里使用模块模式如何导致代码的更快/缓存版本?

最佳答案

基本上,在不使用闭包的情况下,mixin 函数将在每个使用 mixin 的时间。通过创建闭包,每个函数都将创建一次,mixin 每次创建时都会引用这些函数叫。由于 mixin 不必每次都重新创建这些函数运行速度更快。

没有关闭

var asRectangle = function() {
// every time this function is called, these three functions are created
// from scratch, slowing down execution time
this.area = function() {
return this.length * this.width;
}
this.grow = function() {
this.length++, this.width++;
}
this.shrink = function() {
this.length--, this.width--;
}
})();

关闭

var asRectangle = (function() {
// these functions are 'cached' in the closure
function area() {
return this.length * this.width;
}
function grow() {
this.length++, this.width++;
}
function shrink() {
this.length--, this.width--;
}

// this function is set to asRectangle. it references the above functions
// every time it is called without having to create new ones
return function() {
this.area = area;
this.grow = grow;
this.shrink = shrink;
return this;
};
})();

关于javascript - JS 模块模式 = 缓存/更好的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13366708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com