Skip to content

Commit

Permalink
Try not to pre-alloc space for the vec, see if the performance changes.
Browse files Browse the repository at this point in the history
  • Loading branch information
drink7036290 committed Dec 5, 2024
1 parent cf48675 commit 5e7e584
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions implementations/q146_lru_cache/src/impl_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::time::SystemTime;
pub struct LRUCache {
arr: Vec<HeapNode>,
map: HashMap<i32, usize>, // key -> vec's index
capacity: usize,
}

/**
Expand Down Expand Up @@ -142,8 +143,9 @@ impl LRUCache {

pub fn new(capacity: i32) -> Self {
Self {
arr: Vec::with_capacity(capacity as usize),
map: HashMap::with_capacity(capacity as usize),
arr: Vec::new(),
map: HashMap::new(),
capacity: capacity as usize,
}
}

Expand Down Expand Up @@ -172,7 +174,7 @@ impl LRUCache {
let index = match self.map.get(&key) {
Some(v) => *v,
None => {
if self.arr.len() == self.arr.capacity() {
if self.arr.len() == self.capacity {
let last_index = self.arr.len() - 1;

self.swap_nodes(0, last_index);
Expand Down

0 comments on commit 5e7e584

Please sign in to comment.