0
0
R Programmingprogramming~5 mins

R6 classes in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: R6 classes
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the vector size grows, the time to sum all elements grows roughly in direct proportion.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: Doubling the input roughly doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to sum the data grows linearly with the number of elements stored in the object.

Common Mistake

[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.

Interview Connect

Understanding how methods inside R6 classes scale with data size helps you write efficient code and explain your design choices clearly.

Self-Check

"What if the sumData method only summed the first 10 elements? How would the time complexity change?"