LRU是最近最少使用页面置换算法(Least Recently Used),也就是首先淘汰最长时间未被使用的页面
* LRU_Cache.php
<?php
/**
* Created by PhpStorm.
* User: mingzhanghui
* Date: 1/10/2020
* Time: 14:40
*/
class LRU_Cache
{
/** @var array */
private $map;
/** @var int */
private $cap = 0;
/**
* LRU_Cache constructor.
* @param $size int
*/
public function __construct($size) {
$this->map = array();
$this->cap = $size;
}
/**
* @param $key string
* @param $value mixed
*/
public function setValue($key, $value) {
// 如果存在,则向队尾移动,先删除,后追加
if (isset($this->map[$key])) {
unset($this->map[$key]);
}
// 长度检查, 超长则删除首元素
if (count($this->map) >= $this->cap) {
array_shift($this->map);
}
// 队尾追加元素
$this->map[$key] = $value;
}
/**
* @param $key
* @return mixed|null
*/
public function getValue($key) {
$ret = null;
if (isset($this->map[$key])) {
$ret = $this->map[$key];
// 移动到队尾
unset($this->map[$key]);
$this->map[ $key ] = $ret;
}
return $ret;
}
/**
* @return false|string
*/
public function __toString() {
return json_encode($this->map);
}
}
测试代码:
* index.php
<?php
/**
* Created by PhpStorm.
* User: mingzhanghui
* Date: 1/10/2020
* Time: 14:50
*/
include "LRU_Cache.php";
$cache = new LRU_Cache(5);
$cache->setValue("01", "a");
$cache->setValue("02", "b");
$cache->setValue("03", "c");
$cache->setValue("04", "d");
$cache->setValue("05", "e");
printf("%s\n", $cache);
$cache->setValue("06", "f");
printf("%s\n", $cache);
$cache->setValue("03", "g");
printf("%s\n", $cache);
$cache->setValue("07", "h");
printf("%s\n", $cache);
$cache->setValue("01", "xxx");
printf("%s\n", $cache);
php index.php
{"01":"a","02":"b","03":"c","04":"d","05":"e"}
{"02":"b","03":"c","04":"d","05":"e","06":"f"}
{"02":"b","04":"d","05":"e","06":"f","03":"g"}
{"04":"d","05":"e","06":"f","03":"g","07":"h"}
{"05":"e","06":"f","03":"g","07":"h","01":"xxx"}
缓存中始终5个元素 始终淘汰array首个元素,查询或者设置key,会使对应的KeyValuePair到array末尾