Subscribe to DSC Newsletter

I've found the following tweet by Winston Chang. For whatever reasons, it went viral. It compares two pieces of code doing the same thing, but the one at the bottom runs 300 times faster.

#rstats performance tip: if you must grow a vector in a loop, make sure there's only one reference to it so that R doesn't have to make a copy on each iteration.

# 6 seconds:
x <- integer()
for(i in 1:5e4) x <- c(x, i)

# 0.02 seconds:
x <- integer()
for(i in 1:5e4) x[i] <- i

Views: 1024

Reply to This

Replies to This Discussion

it's really amazing!


© 2021   TechTarget, Inc.   Powered by

Badges  |  Report an Issue  |  Privacy Policy  |  Terms of Service