Helin Wang
Helin Wang

Reputation: 4202

How can Clone::clone_from avoid unnecessary allocations?

The documentation of clone_from says:

Performs copy-assignment from source.

a.clone_from(&b) is equivalent to a = b.clone() in functionality, but can be overridden to reuse the resources of a to avoid unnecessary allocations.

Why does clone_from (copy-assignment) avoid unnecessary allocations? What is an example?

I think this is a well known concept in C++, but I don't have a strong C++ background.

Upvotes: 5

Views: 1704

Answers (1)

mcarton
mcarton

Reputation: 30051

Let's take for example two vectors a and b. Each vector has to allocate an internal buffer to store the elements.

Here is what happens for each case:

  • a = b.clone() always executes b.clone(), which creates a brand new vector with its own buffer, then a = brand_new_vector throws away a's buffer and steals the one from brand_new_vector.
  • a.clone_from(&b): If a's buffer is too small, it will allocate a big enough buffer, but if a's buffer is already big enough, it will copy each element from b directly to a's buffer. In the latter case, a's buffer was recycled and a memory allocation was avoided.

Upvotes: 11

Related Questions