You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[perf] Constructors where this escapes are slow #582
fnnew() -> Self{let this = Self{ ...};
... body of the constructor ...
this
}
When this escapes in the body of the constructor, for example init(&mut this), the translated new becomes slower than necessary: this is constructed inside the body then memcpy'ed in the caller.
When this does not escape in the body of the constructor, Rust returns the this inline, without a memcpy. See this example.
C++ does no memcpy. The semantics of the constructor is: a storage, i.e. this, is passed to the constructor, the constructor initialises this, then the storage is returned.
I think that the solution for this performance problem is to follow what C++ does: create this before calling the constructor and pass the storage to the constructor. This would also fix #248.
In performance terms, refcount is worse because it does 3 memcpy's even when this does not escape:
fnnew() -> Self{let __this = Rc::new(RefCell::new(Self{ ...}));let this = __this.as_pointer();Rc::try_unwrap(this)// memcpy 1: transforms Rc<RefCell<S>> into Result<RefCell<S>, Rc<RefCell<S>>>.ok().unwrap()// memory 2: transforms Result<RefCell<S>, Rc<RefCell<S>>> into RefCell<S>.into_inner()// memcp 3: transforms RefCell<S> into S}
The solution is the same as unsafe: create this before calling the constructor and pass the storage to the constructor.
Also the create this before calling the constructor and pass the storage to the constructor strategy is what we need when we will implement placement new.
Activity
lucic71 commentedon Nov 2, 2026
This also impacts the performance of new.
Per
new S(args), for anSof N bytes:new S(args)Box::leak(Box::new(S::new(args)))Ptr::alloc(S::new(args))Rcinside the constructor,Rcinside Ptr)Rcinside the constructor)Box::new); 2 if the constructor body calls a method onthistry_unwrap,.ok(),into_inner,Rc::newinalloc)In unsafe
Box::newdoes at least one allocation becauseS::new(args)first builds S on stack then memcopies it into the heap Box.lucic71 commentedon Nov 2, 2026
Also the
create this before calling the constructor and pass the storage to the constructorstrategy is what we need when we will implement placement new.nunoplopes commentedon Nov 21, 2026
Not much we can do here