S3 object system in R Programming - Time & Space Complexity
When working with the S3 object system in R, it's important to understand how method dispatch affects performance.
We want to know how the time to find and run a method grows as we add more classes or methods.
Analyze the time complexity of method dispatch in the S3 system.
print.myclass <- function(x) {
cat("This is myclass object\n")
}
obj <- structure(list(), class = c("myclass", "list"))
print(obj)
This code defines a print method for class "myclass" and calls print on an object with two classes.
When R calls print(obj), it looks for a matching method by checking classes in order.
- Primary operation: Searching the class vector for a matching method.
- How many times: Once per class in the object's class attribute, in order.
As the number of classes in the object grows, R checks each class one by one until it finds a method.
| Number of Classes (n) | Approx. Checks |
|---|---|
| 2 | Up to 2 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows linearly with the number of classes.
Time Complexity: O(n)
This means the time to find the right method grows in a straight line as the number of classes increases.
[X] Wrong: "Method dispatch happens instantly no matter how many classes there are."
[OK] Correct: Actually, R checks each class in order, so more classes mean more checks and more time.
Understanding how method dispatch scales helps you write efficient code and explain how R handles objects behind the scenes.
"What if the object had only one class? How would the time complexity change?"