Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is source speed different from RStudio console line code?

Tags:

r

rstudio

I have a script with self-written functions (no plots). When I copy-paste that script into the R-Studio console, it takes ages to execute, but when I use source("Helperfunctions.R") it doesn't take more than a second.

Question: Where does the difference in speed come from?

I am aware of two differences between running code via the source() function vs. entering code at the R-Studio console:

From ?source:

Since expressions are not executed at the top level, auto-printing is not done.

The way I understand this: source() will not plot graphs (unless made specific with e.g. print(plot)), while the R Studio console codes will always plot graphs. I'm sure this will affect the speed of execution to a certain degree, but this seems irrelevant in my case, because there are barely any plot calls.

And:

(...) the complete file is parsed before any of it is run

I have been working with R for a while now, but I'm not sure whether this relevant for the speed-issue I'm having. Is it possible that completely parsing all code "before any of it is run" speeds up the execution of my helper functions script by a factor of a hundred?

Edit: I'm using R version 3.2.3.

like image 868
KenHBS Avatar asked Aug 23 '16 08:08

KenHBS


1 Answers

The issue is not source() vs. console line code. Instead, it is an issue of how RStudio sends code from the source pane to the console.

When I copy the content of Helperfunctions.R and run it in RGui (instead of RStudio), the code is executed with nearly the same speed as when I use source("Helperfunctions.R") in RStudio.

Apparently, lines of code always (?) require more execution time in RStudio than in RGui. Even though you may usually not notice the time-difference when executing a couple of lines in the console, it seems to make a huge difference when, say, 3.000 lines of code are being executed in the R Studio console at once.

My understanding is that upon using source("Helperfunctions.R") in the RStudio source pane, the code is not actually sent to the RStudio console (which would have been slow), but is actually executed directly in the R language.

like image 147
KenHBS Avatar answered Sep 18 '22 12:09

KenHBS