S4 object system in R Programming - Time & Space Complexity
When using the S4 object system in R, it is important to understand how the time to create and use objects grows as your program runs.
We want to know how the time changes when we create many objects or call methods on them.
Analyze the time complexity of the following code snippet.
setClass("Person", slots = list(name = "character", age = "numeric"))
createPeople <- function(n) {
people <- vector("list", n)
for (i in seq_len(n)) {
people[[i]] <- new("Person", name = paste0("Person", i), age = i)
}
people
}
This code defines a class and creates a list of n Person objects, each with a name and age.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop creating each Person object one by one.
- How many times: Exactly n times, once for each object created.
As n grows, the number of objects created grows linearly, so the time grows roughly in a straight line with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 object creations |
| 100 | About 100 object creations |
| 1000 | About 1000 object creations |
Pattern observation: Doubling n roughly doubles the work done.
Time Complexity: O(n)
This means the time to create n S4 objects grows in direct proportion to n.
[X] Wrong: "Creating many S4 objects happens instantly no matter how many."
[OK] Correct: Each object takes time to build, so more objects mean more total time.
Understanding how object creation scales helps you write efficient R code and explain your reasoning clearly in interviews.
"What if we added a nested loop inside the object creation to initialize more data? How would the time complexity change?"