Skip to content

Instantly share code, notes, and snippets.

@nacnudus
Last active May 3, 2020 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nacnudus/04b45ad6c8b2a1e98d28d536e18cea34 to your computer and use it in GitHub Desktop.
Save nacnudus/04b45ad6c8b2a1e98d28d536e18cea34 to your computer and use it in GitHub Desktop.
Fastest way to count objects in an R environment
# Compare performance of ls() with as.list.environment() for counting objects
# length(as.list.environment()) is fastest
env <- environment(plot) # A handy, large environment
bench::mark(length(ls(env)), length(as.list(env)))
# # A tibble: 2 x 13
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc
# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list>
# 1 length(ls(env)) 4.69ms 4.96ms 198. NA 0 99 0 501ms <int [1]> <NULL> <bch:tm> <tibble [99 × 3]>
# 2 length(as.list(env)) 3.44ms 4.03ms 240. NA 0 120 0 500ms <int [1]> <NULL> <bch:tm> <tibble [120 × 3]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment