R slow assignment in setRefClass <p>Perhaps this question should be in some programming forum, but I thought I would ask it in the statistics community. The following code illustrates the problem when performing global assignment in R's setRefClass:</p> <pre><code>class &lt;- setRefClass("class", fields = list( params = "numeric" ), methods = list( initialize = function() { params &lt;&lt;- 5 }, do.stuff = function() { for (i in 1:1e5) params &lt;&lt;- 2 } )) # FAST: params &lt;- 5 time &lt;- Sys.time(); for (i in 1:1e5) params &lt;- 2; time &lt;- Sys.time() - time print(time) # SLOW: newclass &lt;- class$new() time &lt;- Sys.time(); newclass$do.stuff(); time &lt;- Sys.time() - time print(time) </code></pre> <p>And pqR shows a slight improvement in runtime, but nothing drastic.</p> <p>I would like to know why this is happening... in my mind, assigning a variable should be fast. Maybe this has something to do with locating an object "slot" (variable location), similar to S3/S4 classes. I bet I can only observe such behavior with R, and not C++.</p>