memory-safety-optimization-patterns
Instructions for memory safety optimization patterns.
安装与使用
请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。
查看来源 ↗使用指南技能说明
priority: high
Memory Safety & Optimization Patterns
Zero-Copy
-
&stroverString,&[T]overVec<T>in function params -
Cow<T>for conditional ownership (borrow when possible, clone only on mutation) -
Arc<T>for shared immutable data across threads
RAII
Resources released automatically on scope exit via Drop. Mutex/RwLock guards auto-unlock. No manual cleanup needed.
String Handling
-
Cow<str>for conditional String/&str ownership -
Arc<str>for cheap cloning of shared immutable strings -
String::with_capacity()to pre-allocate
Buffer Reuse
-
Vec::clear()+ reuse instead of new allocation - Pre-allocate with
Vec::with_capacity()in hot loops -
SmallVecfor stack-allocated small collections
Lifetimes
- Default to references in function params
- Minimize lifetimes in structs (prefer owned data)
- Use
'_wildcard for unused lifetime bounds
Verification Tools
| Tool | Purpose | Command |
|---|---|---|
| Valgrind | Memory leaks, UAF | valgrind --leak-check=full ./app |
| ASan | Memory errors | RUSTFLAGS="-Z sanitizer=address" cargo +nightly build |
| Miri | Undefined behavior | cargo +nightly miri test |
| Clippy | Lifetime/safety lints | cargo clippy -- -D warnings |
Anti-Patterns
-
Cloneinstead of&T(unnecessary allocation) -
format!()when borrowing suffices - Holding mutex guards across
.awaitpoints -
Box<T>for simple owned data (unnecessary indirection) - No buffer pre-allocation in hot paths
使用示例
查看来源仓库中的使用示例与配置说明。
查看来源 ↗来源历史
- 收录时间
- 2026-03-11
- 索引更新时间
- 2026-03-11
- Branch
- main
收录与同步日期属于本站记录。源码修改历史请查看来源仓库。
GitHub ↗chat Comments (0)
Sign in to join the discussion and leave a comment.
No comments yet. Be the first to share your thoughts!