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

Preallocating memory


Most strongly typed programming languages like C, C++, and Java generally require a vector (or array) to be declared prior to any operation applied on it. This declaration in effect preallocates the memory space that the vector requires. There are special occasions where dynamic memory allocation is used, but this is seldom the first choice mainly because dynamic memory allocation slows down a program. Every time a vector is resized, the program needs to perform extra steps that include copying the vector to a larger or smaller memory block and deleting the old vector. These steps are not needed if the memory is preallocated.

When it comes to preallocating memory, R is no different from the other programming languages. However, being an interpreted language, it imposes less control, thus it is easy for users to overlook this—R will not throw any compilation error if a vector's memory is not preallocated. Nevertheless, not preallocating memory in R can result in significantly...