KnockoutJS:计算与纯计算

KnockoutJS: computed vs. pureComputed

KnockoutJS 中 computedpureComputed 有什么区别?

我可以安全地使用 pureComputed 而不是 computed 吗?

它们非常相似。 The difference is pureComputed 进行了一些性能优化,并通过智能识别谁在跟踪其更改来尝试防止内存泄漏。

在很多情况下,您可以安全地将 computed 替换为 pureComputed。计算后的函数 should follow this:

1.Evaluating the computed observable should not cause any side effects.

2.The value of the computed observable shouldn’t vary based on the number of evaluations or other “hidden” information. Its value should be based solely on the values of other observables in the application, which for the pure function definition, are considered its parameters.

因此,根据经验,任何只是简单地转换一些常规 observable 属性的计算可观察对象都应该像 pureComputed 一样好,否则坚持使用 computed.

The documentation has decent explanations of when/why 你应该 使用 pureComputed observables。以下是相关摘录:

You should not use the pure feature for a computed observable that is meant to perform an action when its dependencies change.

The reason you shouldn’t use a pure computed if the evaluator has important side effects is simply that the evaluator will not run whenever the computed has no active subscribers (and so is sleeping). If it’s important for the evaluator to always run when dependencies change, use a regular computed instead.

我同意@Jeroen 的观点,我想添加一个来自 J. Munro 的 book 的简短示例,它对我帮助很大,所以这可能对其他人也有帮助。

首先,pureComputed observables 与 computed observables 非常相似,具有多项性能和内存改进。该名称是从 Pure function 编程术语借用的,它意味着任何仅使用局部变量的函数都可能是纯函数,而任何使用非局部变量的函数都可能是不纯的。

Knockout.js 中的可观察对象的处理方式不同。因此,pureComputed observables 被置于休眠模式(Knockout 倾斜所有依赖项并在阅读后重新评估内容)并且 computed observables 被置于监听模式(Knockout 在首次访问之前不断检查值是否是最新的) .

因此,如果您需要执行其他代码,那么最好使用计算的可观察对象。

function ViewModel() {
     var self = this;

     self.firstName = ko.observable('Arshile');
     self.lastName = ko.observable('Gorky');
     self.pureComputedExecutions = 0;
     self.computedExecutions = 0;

     self.pureComputedFullName = ko.pureComputed(function() {
         // This is NOT recommended 
         self.pureComputedExecutions++;
         return 'Hello ' + self.firstName() + ' ' + self.lastName();
     });
     self.computedFullName = ko.computed(function() {
         self.computedExecutions++;

         return 'Hello ' + self.firstName() + ' ' + self.lastName();
     });
 };
 var viewModel = new ViewModel();
 ko.applyBindings(viewModel);

 alert('Pure computed executions: ' + viewModel.pureComputedExecutions);
 alert('Computed executions: ' + viewModel.computedExecutions);

当此代码为 运行 时,会显示两条警告消息,显示调用 pureComputed 和 computed 函数的次数。由于 pureComputed 处于休眠模式,因此该函数从未被访问过,计数器将显示 0。与此相反,计算函数在数据绑定时自动计算,导致计数器增加数字并显示 1.