Understanding object.size() versus nchar()

前端 未结 1 1169
旧时难觅i
旧时难觅i 2021-01-22 05:12

Consider the following vectors x and y

x <- \"a\"
y <- deparse(x)

From ?nchar

1条回答
  •  礼貌的吻别
    2021-01-22 05:50

    Not necessarily. You typically don't set aside the exact amount of memory you need for a string since that it makes it difficult to skip around and find the one you need in memory, so allocations will happen in chunks. Observe

    rv<-1:100
    os<-sapply(rv, function(x) object.size(paste0(rep("a",x), collapse="")))
    plot(rv,os, xlab="string length", ylab="object size")
    

    enter image description here

    Here we create strings "a","aa","aaa","aaaa", etc and see the object size. Note the size of the object does not increase with each additional character, but when you pass a threshold, you get a larger chunk assigned to you.

    So object size doesn't tell you how many bytes the data is actually taking up, it just tells you how many bytes have been set aside. There are not really the same thing.

    0 讨论(0)
提交回复
热议问题