PHP:在静态变量或类属性中缓存加载的数据的效率如何?
我遇到过函数和类方法,它们通过ID将加载的数据存储到静态变量或类属性中,并在继续之前检查变量/属性中是否存在ID。如果ID存在,它将从变量/属性返回“缓存”数据。如果没有,则加载数据,然后将其存储在变量/属性中PHP:在静态变量或类属性中缓存加载的数据的效率如何?,php,oop,caching,static,Php,Oop,Caching,Static,我遇到过函数和类方法,它们通过ID将加载的数据存储到静态变量或类属性中,并在继续之前检查变量/属性中是否存在ID。如果ID存在,它将从变量/属性返回“缓存”数据。如果没有,则加载数据,然后将其存储在变量/属性中 class MyProducts { public $products = array(); 然后加载器方法如下所示: public function loadProduct($product_id) { if(isset($this->products[$product
class MyProducts {
public $products = array();
然后加载器方法如下所示:
public function loadProduct($product_id) {
if(isset($this->products[$product_id])) return $this->products[$product_id];
// otherwise do all the data loading into $product_data; pretend code is
// here to pull data; now store it
$this->products[$product_id] = $product_data;
}
我还看到它直接在这样一个函数中完成:
function loadProduct($product_id) {
static $myproducts = array();
if(isset($myproducts[$product_id])) return $myproducts[$product_id];
// otherwise do all the data loading into $product_data; pretend code is
// here to pull data; now store it
$myproducts[$product_id] = $product_data;
}
这样做的效率有多高,“缓存”数据的使用时间有多长?我试着读了几篇关于这个主题的文章,但最后还是弄糊涂了。我知道我们确实利用了memcache,在我读到的文章中也提到了它
谢谢 在第一个示例中,
$myproducts
可以通过$this->myproducts
在类中的任何方法获得。在第二个示例中,$myproducts
仅在该函数中可用,其他任何地方都不可用。明白了,谢谢!我刚刚了解到,数据只会在当前脚本执行过程中持续存在。在我给出的示例中,我们只加载一次产品数据,因此它看起来毫无意义。但是,我也看到它用于缓存配置的设置,这些设置在整个执行过程中被多次加载,因此我可以肯定地看到它的优点;这些值不是每个实例的值,而是为任何调用共享的值:。如果计算和/或检索的成本很高,那么在执行过程中缓存仍然有价值,如果您要多次接触它,但是如果您需要在执行之间缓存它,那么您可能需要像Redis或Memcached这样的东西来保持它。谢谢大家@Jeto我记得读过一些关于这方面的文章,我相信在过去的一些工作中,这些变量可能更有用。