Skip to content

Commit

Permalink
Hopefully better memory management?
Browse files Browse the repository at this point in the history
  • Loading branch information
Absolucy committed Apr 14, 2024
1 parent 23ad2e1 commit ce3fc2a
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
9 changes: 8 additions & 1 deletion crates/logger/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,14 @@ static MESSAGE_QUEUE: Lazy<Mutex<LogQueues>> =
/// Any existing log messages will still be written to the log file.
pub fn clear_log_queue() {
if let Some(queue) = Lazy::get(&MESSAGE_QUEUE) {
queue.lock().clear();
let mut queue = queue.lock();
if queue.capacity() > DEFAULT_CAPACITY {
// Don't use clear(), so we reclaim memory.
*queue = AHashMap::with_capacity(DEFAULT_CAPACITY);
} else {
// If we're at the default capacity, it's a waste of time to reallocate.
queue.clear();
}
}
let start = Instant::now();
while THREAD_COUNT.load(Ordering::SeqCst) > 0 {
Expand Down
13 changes: 11 additions & 2 deletions crates/rand/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,21 @@ use once_cell::sync::Lazy;
use parking_lot::Mutex;
use slotmap::SlotMap;

const DEFAULT_CAPACITY: usize = 16;

static INSTANCES: Lazy<Mutex<SlotMap<ByondSlotKey, RngDispatcher>>> =
Lazy::new(|| Mutex::new(SlotMap::with_capacity_and_key(128)));
Lazy::new(|| Mutex::new(SlotMap::with_capacity_and_key(DEFAULT_CAPACITY)));

pub(crate) fn free_instances() {
if let Some(instances) = Lazy::get(&INSTANCES) {
instances.lock().clear();
let mut instances = instances.lock();
if instances.capacity() > DEFAULT_CAPACITY {
// Don't use clear(), so we reclaim memory.
*instances = SlotMap::with_capacity_and_key(DEFAULT_CAPACITY);
} else {
// If we're at the default capacity, it's a waste of time to reallocate.
instances.clear();
}
}
}

Expand Down
13 changes: 11 additions & 2 deletions crates/regex/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,21 @@ use parking_lot::RwLock;
use regex::Regex;
use slotmap::SlotMap;

const DEFAULT_CAPACITY: usize = 16;

static INSTANCES: Lazy<RwLock<SlotMap<ByondSlotKey, Regex>>> =
Lazy::new(|| RwLock::new(SlotMap::with_capacity_and_key(128)));
Lazy::new(|| RwLock::new(SlotMap::with_capacity_and_key(DEFAULT_CAPACITY)));

pub(crate) fn free_instances() {
if let Some(instances) = Lazy::get(&INSTANCES) {
instances.write().clear();
let mut instances = instances.write();
if instances.capacity() > DEFAULT_CAPACITY {
// Don't use clear(), so we reclaim memory.
*instances = SlotMap::with_capacity_and_key(DEFAULT_CAPACITY);
} else {
// If we're at the default capacity, it's a waste of time to reallocate.
instances.clear();
}
}
}

Expand Down

0 comments on commit ce3fc2a

Please sign in to comment.