R6 classes in R Programming - Time & Space Complexity
When using R6 classes in R, it's important to understand how the time to run methods grows as the data or operations increase.
We want to see how the cost changes when calling methods on R6 objects with different input sizes.
Analyze the time complexity of the following R6 class method.
library(R6)
MyClass <- R6Class("MyClass",
public = list(
data = NULL,
initialize = function(vec) {
self$data <- vec
},
sumData = function() {
sum(self$data)
}
)
)
obj <- MyClass$new(1:1000)
obj$sumData()
This code defines an R6 class that stores a vector and sums its elements when asked.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Summing all elements in the stored vector.
- How many times: The sum function internally goes through each element once.
As the vector size grows, the time to sum all elements grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the input roughly doubles the work done.
Time Complexity: O(n)
This means the time to sum the data grows linearly with the number of elements stored in the object.
[X] Wrong: "Calling a method on an R6 object always takes the same time no matter the data size."
[OK] Correct: The method's work depends on the data inside the object. If it processes all elements, time grows with data size.
Understanding how methods inside R6 classes scale with data size helps you write efficient code and explain your design choices clearly.
"What if the sumData method only summed the first 10 elements? How would the time complexity change?"