[英]compute if first time, load if second time pattern
I want to ask if using this pattern is a good practice or not: 我想问一下使用这种模式是否是一个好习惯:
I have a class that contains some raw data. 我有一个包含一些原始数据的类。 I want to conclude some information from this data for example:
我想从这些数据中得出一些信息,例如:
class my_class{
public:
int get_integers_sum();
private:
std::vector<int> all_integers;
};
assuming that the all_integers is not going to be changed. 假设不会更改all_integers。 Is it a good to do this :
这样做很好吗?
class my_class{
public:
int get_integers_sum(){
if(sum==-1){
sum=sum=std::acculmate(all_integeres);// the proper code ofcourse
}
return sum;
}
private:
std::vector<int> all_integers;
int sum=-1;
};
This is a useful pattern when you know that the input will not change. 当您知道输入将不会更改时,这是一个有用的模式。 The general name for this approach is memoization .
这种方法的通用名称是备忘录 。 Your implementation is a bit flawed since the sum of
all_integers
might actually be -1. 您的实现有些缺陷,因为
all_integers
的总和可能实际上为-1。
Measure it and find out; 测量并找出; never try to optimise without measuring.
永远不要尝试优化而不测量。 Bear in mind that on modern CPUs computation is fast and memory access is slow, so the answers may not be what you expect.
请记住,在现代CPU上,计算速度很快而内存访问速度很慢,因此答案可能并非您所期望的。
And that's before you worry about multiple threads safely calling this code. 那是在您担心多个线程安全地调用此代码之前。
As far as I know, this type of caching method is fine. 据我所知,这种缓存方法很好。 It basically makes sense when you know that get_integers_sum() gets called quite often, but all_integers changes very rarely.
当您知道get_integers_sum()经常被调用而all_integers很少更改时,这基本上是有道理的。 But you should keep const correctness and this is one of the cases it's ok to use mutable.
但是您应该保持const的正确性,这是使用可变的情况之一。
class my_class{
public:
int get_integers_sum() const { // <- adding const
if(sum==-1){
sum=std::acculmate(all_integeres);
}
return sum;
}
private:
std::vector<int> all_integers;
mutable int sum=-1; // <- adding mutable so it can be changed in const function
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.