Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Memory allocation for objects in R

I am trying to understand the memory allocation in R.
So I populated 2 methods with same results. So Does this mean method with lesser allocation is efficient

For example

## Method 1
f <- function(num) {
  for(i in seq_len(num)) {
    cat("Hello, world!\n") }}

object.size(f(1))
Hello, world!
  0 bytes

## Method 2
asd <- "Hello, world!"
object.size(asd)
120 bytes

So if you see above, Method 1 is more efficient than Method 1 right? (0 and 120 bytes respectively)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is my understanding correct?

>Solution :

You are not comparing like with like. Your function prints "Hello, world!" but returns nothing. Therefore when you run object.size(f(1)), you are essentially running object.size(NULL), which is 0 (the size of nothing).

If you change your function so that it returns a string, it would be equivalent to Method 2 (assigning a value to a string):

f <- function(num) {
    for (i in seq_len(num)) {
        return("Hello, world!\n")
    }
}

object.size(f(1)) # 120 bytes
object.size(f(1)) == object.size("Hello, world!") # TRUE

In either case you are measuring the size of the string. However, simply allocating the string in this case is going to use less RAM, as the function itself takes up space in memory:

object.size(f) # 16088 bytes

Even an empty function in R will take up about 4k of RAM:

g  <- function() {
    return(TRUE)
}
object.size(g) # 4384 bytes

Having said this, given that in R you are generally working with data held in RAM, the amount of overhead storing functions is usually negligible by comparison. Most of the time in R you will want to optimise for clarity of your code (i.e. use functions), rather than small amounts of RAM. There are exceptions though (e.g. calling a function millions of times in a loop).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading