Why does list classification slow down the lengths () function?

I just noticed that classifying a list by adding an extra label to the attribute class(S3) or defining a new parent class (S4) drastically slows down the basic operation lengths().

This suggests that I should always open the "classified list" before the call lengths().

Can anyone

  • explain why this is happening and / or

  • propose a better solution (or explain why this is not a big deal since the differences are only microseconds in absolute terms).

Playable Code:

# create a list of 1,000 elements with variable letter lengths
mylist <- list()
length(mylist) <- 1000
set.seed(99)
mylist <- lapply(mylist, function(x) sample(LETTERS, size = sample(1:100, size = 1), 
                                            replace = TRUE))

# create an S3 "classed" version
mylist_S3classed <- mylist
class(mylist_S3classed) <- c("myclass", "list")

# create an S4 classed version
setClass("mylist_S4class", contains = "list")
mylist_S4classed <- new("mylist_S4class", mylist)

# compare timings of lengths
microbenchmark::microbenchmark(lengths(mylist),
                               lengths(mylist_S3classed), 
                               lengths(mylist_S4classed),
                               unit = "relative")
## Unit: relative
##                      expr      min       lq     mean    median        uq       max neval
##           lengths(mylist)   1.0000   1.0000   1.0000   1.00000   1.00000   1.00000   100
## lengths(mylist_S3classed) 125.1433 119.3588 103.9747  91.90734  89.56034 291.97767   100
## lengths(mylist_S4classed) 162.4045 155.4870 119.0611 120.20908 111.95417  67.55309   100

## in absolute timings
microbenchmark::microbenchmark(lengths(mylist),
                               lengths(mylist_S3classed), 
                               lengths(mylist_S4classed))
## Unit: microseconds
##                      expr      min        lq       mean    median       uq      max neval
##           lengths(mylist)    6.401    6.9475    9.66612    9.4620   10.577   29.237   100
## lengths(mylist_S3classed)  792.738  851.0895  911.97067  898.0955  939.558 1604.189   100
## lengths(mylist_S4classed) 1050.448 1104.7920 1293.63965 1173.4545 1229.485 6431.130   100
+4
source share
1 answer

- , R, length. , , . , .

, S3 S4, R length, length . , R , , . , , .

, "", length , ...

+5

Source: https://habr.com/ru/post/1665030/


All Articles