2024-05-28. PDF
Rewrite It In Rust
struct Container {
items: Vec<i32>,
}
fn loop_items(&mut self) {
for i in self.items.iter_mut() {
self.do_something(i)
}
}
fn do_something(&self, i: &i32) {}
| for i in self.items.iter_mut() {
| ---------------------
| |
| mutable borrow occurs here
| mutable borrow later used here
| self.do_something(i)
| ^^^^^^^^^^^^^^^^^^^^ immutable borrow occurs here
解决方案:内部可变性(RefCell、Mutex)
struct Container {
items: RefCell<Vec<i32>>,
}
fn loop_items(&self) {
for i in self.items.borrow_mut().iter_mut() {
self.do_something(i)
}
}
fn do_something(&self, i: &i32) { }
fn foo(s: &str, some_condition: bool) -> &str {
if some_condition {
&s.replace("foo", "bar")
} else {
s
}
}
| &s.replace("foo", "bar")
| ^-----------------------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
fn foo(s: &str, some_condition: bool) -> Cow<str> {
if some_condition {
Cow::from(s.replace("foo", "bar"))
} else {
Cow::from(s)
}
}
协作式执行
Async 中避免长时间堵塞的逻辑!!! Tokio #4730
编译单元(Codegen Units)
cargo build --timings
程序的内存布局
申请 HEAP 的 API
// syscall
int brk(void *addr);
void *mmap(void addr, size_t length, int prot, int flags,
int fd, off_t offset);
// glibc
void *malloc( size_t size );
void free( void *ptr );
操作 | 耗时(纳秒) |
---|---|
syscall | 100-300 |
funcall | 1-2 |
分类 | 大小 |
---|---|
Small | [16, 32, 48, …, 128], [192, 256, 320, …, 512], [768, 1024, 1280, …, 3840] |
Large | [4 KiB, 8 KiB, 12 KiB, …, 4072 KiB] |
Huge | [4 MiB, 8 MiB, 12 MiB, …] |
struct Pool<T> {
items: Vec<T>
}
fn pull(&mut self) -> T;
fn attach(&mut self, T);
CPU 节约 10%!
高吞吐场景下的对象池
引用计数(RC) | 👎 |
GC(sync.Pool) | 👍 |