Book Image

R High Performance Programming

Book Image

R High Performance Programming

Overview of this book

Table of Contents (17 chapters)
R High Performance Programming
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Reusing objects without taking up more memory


The first tweak takes advantage of how R manages the memory of objects using a copy-on-modification model. In this model, when a copy of an object x is made, for example with y <- x, it is not actually copied in the memory. Rather, the new variable y simply points to the same block of memory that contains x. The first time when y is modified, R copies the data into a new block of memory so that x and y have their own copies of the data. That is why this model of memory management is called copy-on-modification. What this means is that new objects can sometimes be created from existing objects without taking up additional memory. To identify potential memory bottlenecks and manage the memory utilization of R programs, it is helpful to understand when R copies data and when it does not.

Take for example the following code, which generates a numeric vector x with 1 million elements and creates a list y that contains two copies of x. We can examine...