何回も使うリストの要素は変数に突っ込んでおいた方がいい
当たり前のお話ですが、何回もアクセスするなら代入コスト払っても、一時変数使った方がよさげ。
> x <- list(list(a=1:3, b=100:103), list(a=2:4, b=200:203)) > system.time(sapply(1:10^6, function(i){ + force(x[[2]]$a[[2]]) + force(x[[2]]$a[[2]]) + force(x[[2]]$a[[2]]) + })) user system elapsed 6.95 0.00 6.95 > system.time(sapply(1:10^6, function(i){ + hoge <- x[[2]]$a[[2]] + force(hoge) + force(hoge) + force(hoge) + })) user system elapsed 4.88 0.01 4.95
リストのリストの場合、変数を2回以上使うなら代入した方が速かった。
アクセス一回のケース
> system.time(sapply(1:10^6, function(i){ + force(x[[2]]$a[[2]]) + })) user system elapsed 3.12 0.00 3.13 > system.time(sapply(1:10^6, function(i){ + hoge <- x[[2]]$a[[2]] + force(hoge) + })) user system elapsed 3.43 0.00 3.44
アクセス二回のケース
> system.time(sapply(1:10^6, function(i){ + force(x[[2]]$a[[2]]) + force(x[[2]]$a[[2]]) + })) user system elapsed 4.80 0.00 4.83 > system.time(sapply(1:10^6, function(i){ + hoge <- x[[2]]$a[[2]] + force(hoge) + force(hoge) + })) user system elapsed 3.84 0.00 3.87