some_list <- list()
for (i in 1:1000) {
some_list[[i]] <- i
}
我想知道,如果some_list成为矢量,这是否效率不高?
答案 0 :(得分:4)
答案似乎是“是”。您可以对其进行基准测试。
f = function() {
some_list <- list()
for (i in 1:100000)
some_list[[i]] <- i
}
g = function() {
some_vector <- c()
for (i in 1:100000)
some_vector[i] <- i
}
h = function() {
some_list <- vector("list", 100000)
for (i in 1:100000)
some_list[[i]] <- i
}
k = function() {
some_vector <- integer(100000)
for (i in 1:100000)
some_vector[i] <- i
}
microbenchmark::microbenchmark(f(), g(), h(), k(), times = 10)
Unit: milliseconds
expr min lq mean median uq max neval
f() 27.723670 28.058052 31.043727 28.812197 33.973669 38.58484 10
g() 20.699626 21.235849 23.029765 21.531695 26.419720 28.04681 10
h() 7.056399 7.151585 7.887856 7.356198 7.936945 10.80190 10
k() 6.025570 6.076456 7.194970 6.408183 7.808957 11.00644 10