性能优化
This commit is contained in:
@@ -10,7 +10,7 @@
|
||||
//! - 返回 base64 data URL 而非文件路径,避免独立弹窗窗口的 asset 协议配置问题
|
||||
//! - 磁盘缓存避免重复 Windows API 调用(昂贵),内存缓存避免重复磁盘读取 + 编码
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -18,26 +18,32 @@ use base64::Engine as _;
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
// ===== 内存缓存 =====
|
||||
static MEM_CACHE: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);
|
||||
/// (path → data URL) + FIFO 淘汰队列(队头最旧,超限时先淘汰)
|
||||
static MEM_CACHE: Mutex<Option<(HashMap<String, String>, VecDeque<String>)>> = Mutex::new(None);
|
||||
const MEM_CACHE_MAX: usize = 512;
|
||||
|
||||
fn mem_get(path: &str) -> Option<String> {
|
||||
let cache = MEM_CACHE.lock().ok()?;
|
||||
cache.as_ref()?.get(path).cloned()
|
||||
cache.as_ref()?.0.get(path).cloned()
|
||||
}
|
||||
|
||||
fn mem_put(path: String, url: String) {
|
||||
if let Ok(mut guard) = MEM_CACHE.lock() {
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
let slot = guard.get_or_insert_with(|| (HashMap::new(), VecDeque::new()));
|
||||
let (map, order) = &mut *slot;
|
||||
if map.contains_key(&path) {
|
||||
// 已存在:仅更新值,不重复入队
|
||||
map.insert(path, url);
|
||||
return;
|
||||
}
|
||||
if map.len() >= MEM_CACHE_MAX {
|
||||
// 简单清理:丢弃一半(最早插入的,HashMap 无序,近似随机)
|
||||
let keep = map.len() / 2;
|
||||
let keys: Vec<String> = map.keys().cloned().collect();
|
||||
for k in keys.iter().skip(keep) {
|
||||
map.remove(k);
|
||||
// FIFO 淘汰最旧条目(O(1)),避免无序淘汰把刚插入的常用图标清掉
|
||||
if let Some(oldest) = order.pop_front() {
|
||||
map.remove(&oldest);
|
||||
}
|
||||
}
|
||||
map.insert(path, url);
|
||||
map.insert(path.clone(), url);
|
||||
order.push_back(path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user