Sobes.tech
Junior — Middle

Explain the principle of the Copy-On-Write (COW) mechanism and in which cases it is used.

sobes.tech AI

Answer from AI

Copy-On-Write (COW) is an optimization technique where copying a resource (such as an array or object) is deferred until it is modified.

Principle of operation:

  • When a copy of an object is created, a reference to the same resource is actually made.
  • As long as the copy is not modified, all use the same resource.
  • When an attempt is made to modify the copy, a real copy of the data occurs ("copy"), and the changes are applied to the new copy.

This allows saving memory and time by avoiding unnecessary copying.

Applications:

  • In systems with a high number of reads and infrequent modifications.
  • In the implementation of immutable data structures.
  • In Node.js, for example, when working with buffers or strings to optimize performance.

Example in pseudocode:

sharedData = [1, 2, 3]
copy1 = sharedData
copy2 = sharedData
// both use the same array
copy1[0] = 10 // now copy1 creates its own copy and modifies it
// copy2 and sharedData remain unchanged