Runnable code:
use std::rc::Rc;
#[derive(Clone, Debug)]
struct State{
pub id:Rc<String>,
}
impl State{
pub fn id(&mut self) {
self.id=Rc::new("".to_string());
}
}
fn place_a_piece<'a>(dedup_ids:&mut Vec<Rc<String>>, states:&mut Vec<State>){
let mut state=State{id:Rc::new("".to_string())};
// In real game program, the following logics will be executed 80000+ times,
// to simplify, shrink it just like this eliding all gaming logics.
let mut spawned_state=state.clone();
dedup_ids.push(Rc::clone(&spawned_state.id));
states.push(spawned_state);
}
fn main(){
let size=90_000;
let mut dedup_ids:Vec<Rc<String>>=Vec::with_capacity(size);
let mut state:Vec<State>=Vec::with_capacity(size);
let now = std::time::Instant::now();
for _ in 0..90_000 {
place_a_piece(&mut dedup_ids, &mut state);
}
println!("{:?}", now.elapsed());
}
Expectations:
- Let State be real owner of State.id's content.
- Anywhere else containers like 'dedup_ids' only holds some kind of reference pointing to State.id without copying its content around.
What I did:
- Using Rc instead of String.clone() in function place_a_piece().
What I found:
- It turns out Rc does not make big difference at all.
Issues:
- Is lifetime a faster solution? How?
- What could be the speedy way to fulfill the expectation? I'm desperate for speed.
- Is the manual way of cloning State is a faster way to do the same job than simply using Clone in attributes as the code does?