# [R] object size of a matrix and a list

jim holtman jholtman at gmail.com
Thu Mar 19 03:49:02 CET 2009

```You were doing for a small size where the overhead masked the gains.
Here a larger case where you can see the differences:

>  #matrix
>   beta.mat <- matrix(0,nr=500, nc=200)
>
>   #list
>   gamma.mat <- list(a= matrix(1L, 500, 100), b=matrix(1.0, 500, 100))
>
>   object.size(beta.mat)
[1] 800112
>   object.size(gamma.mat)
[1] 600408
> str(gamma.mat)
List of 2
\$ a: int [1:500, 1:100] 1 1 1 1 1 1 1 1 1 1 ...
\$ b: num [1:500, 1:100] 1 1 1 1 1 1 1 1 1 1 ...
>

How big do you expect your data items to get?  No need to try to
optimize if they are not large (e.g., taking up 10% of your available
memory).

On Wed, Mar 18, 2009 at 10:14 PM, Kyeongmi Cheon <katie.cheon at gmail.com> wrote:
> Hello,
> My program calculates several variables at each iteration and some of them are
>
> integers and the rest are numeric. When I save them into a matrix, all of them
>
> are of numeric type, of course.
>
> I'm trying to find a way to save time/memory of my program and I was thinking
>
> that it might help to force some variables to be of integer type and the other
>
> columns numeric type.
>
> But when I actually tried it, I found it contrary. A list that has mixtures of
>
> integers and doubles are larger in size than a matrix that has only doubles. Do
>
> lists always take up more space than matrices if they have the same/similar
>
> variables? I just want to know it for the sake of efficiency. Thank
> Kyeongmi
>
>
> My short test program is here:
>
>
>   #matrix
>   beta.mat <- matrix(0,nr=5, nc=2)
>   for (i in 1:5){
>      beta.mat[i,] <- c(i,i*10.0)
>   }
>
>   #list
>   gamma.mat <- list()
>   for (i in 1:5){
>      gamma.mat\$aa[i] <- i
>      gamma.mat\$bb[i] <- i*10.0
>   }
>
>   object.size(beta.mat) #240
>   object.size(gamma.mat) #312
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?

```