Skip to content

[perf] Constructors where this escapes are slow #582

Closed

Description

@lucic71

In unsafe constructors are translated as:

fn new() -> 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:

fn new() -> 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.

Activity

  1. lucic71 commented on Nov 2, 2026

    @lucic71
    ContributorAuthor

    This also impacts the performance of new.

    Per new S(args), for an S of N bytes:

    C++ new S(args) unsafe Box::leak(Box::new(S::new(args))) refcount Ptr::alloc(S::new(args))
    heap allocations 1 1 2 (Rc inside the constructor, Rc inside Ptr)
    heap frees 0 0 1 (Rc inside the constructor)
    whole-object memcpys 0 1 (Box::new); 2 if the constructor body calls a method on this 4 (try_unwrap, .ok(), into_inner, Rc::new in alloc)
    bytes copied 0 N or 2N 4N

    In unsafe Box::new does at least one allocation because S::new(args) first builds S on stack then memcopies it into the heap Box.

  2. lucic71 commented on Nov 2, 2026

    @lucic71
    ContributorAuthor

    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.

  3. nunoplopes commented on Nov 21, 2026

    @nunoplopes
    Contributor

    Not much we can do here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions