Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory size of integer in R

Tags:

r

> object.size(integer(1))
48 bytes
> object.size(numeric(1))
48 bytes

I was trying to estimate how much memory my matrix would take when I found this. I thought integers took 4 bytes and numerics took 8 bytes. What's going on with how R allocates memory?

like image 509
Jean Avatar asked Sep 18 '25 23:09

Jean


2 Answers

R has no scalar data types such as integers or doubles. Instead, every "scalar" value is actually represented as a vector of length 1 and thus has quite a bit of memory overhead. We can confirm this by comparing the size of a scalar to that of a 2-element vector:

object.size(1) == object.size(1:2)
[1] TRUE

The sizes are equal, since R allocates new memory incrementally.

like image 54
ChrKoenig Avatar answered Sep 21 '25 14:09

ChrKoenig


I hasten to add that Jean's finding does not imply that a vector (matrix) of integers requires the same amount of memory as a vector (matrix) of numerics. For example (and credit be to [Paul Murrell] (https://www.stat.auckland.ac.nz/~paul/ItDT/HTML/node76.html)):

> object.size(1:1000)
4040 bytes
> object.size(as.numeric(1:1000))
8040 bytes
like image 35
Jeremy Zechar Avatar answered Sep 21 '25 14:09

Jeremy Zechar