LRU(Least Recently Used) 알고리즘은 가장 오랫동안 사용되지 않은 캐시 항목을 제거하여 새로운 데이터를 저장하는 캐시 교체 알고리즘이다. 이는 제한된 크기의 캐시에서 효율적인 데이터 관리를 위해 사용된다.
캐시의 상태를 (C = {c_1, c_2, ..., c_n}) 라고 할 때,
import 'dart:collection';
class LRUCache<K, V> {
final int capacity;
final LinkedHashMap<K, V> cache = LinkedHashMap();
LRUCache(this.capacity);
V? get(K key) {
if (!cache.containsKey(key)) return null;
V value = cache.remove(key)!;
cache[key] = value;
return value;
}
void put(K key, V value) {
if (cache.containsKey(key)) {
cache.remove(key);
} else if (cache.length >= capacity) {
cache.remove(cache.keys.first);
}
cache[key] = value;
}
void displayCache() {
print("캐시 상태: \${cache.keys.toList()}");
}
}
void main() {
LRUCache<int, String> cache = LRUCache(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.displayCache(); // [1, 2, 3]
cache.get(1);
cache.displayCache(); // [2, 3, 1]
cache.put(4, "D");
cache.displayCache(); // [3, 1, 4] (2가 제거됨)
}
캐시 상태: [1, 2, 3]
캐시 상태: [2, 3, 1]
캐시 상태: [3, 1, 4]
LRU 알고리즘은 캐시 시스템에서 가장 많이 활용되는 방식 중 하나로, 데이터베이스, 운영체제 메모리 관리, 웹 브라우저 캐싱 등에 널리 사용된다. Dart에서 LinkedHashMap을 활용하면 쉽게 구현할 수 있다.