Shiny basics for interactive apps in R Programming - Time & Space Complexity
When building interactive apps with Shiny, it's important to know how the app's response time changes as users interact more or provide larger inputs.
We want to understand how the app's work grows when inputs change or increase.
Analyze the time complexity of the following Shiny server code snippet.
server <- function(input, output) {
output$sum <- renderText({
total <- sum(input$numbers)
paste("Sum is", total)
})
}
This code calculates the sum of a numeric input vector whenever the user changes it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Summing all numbers in the input vector.
- How many times: Once each time the input changes, the sum function goes through all numbers.
As the number of input numbers grows, the time to sum them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of input numbers.
Time Complexity: O(n)
This means the time to update the sum grows in a straight line as the input size grows.
[X] Wrong: "The sum calculation is instant no matter how many numbers there are."
[OK] Correct: Summing requires looking at each number once, so more numbers mean more work and more time.
Understanding how input size affects app responsiveness shows you can build smooth user experiences and write efficient reactive code.
"What if we changed the sum to calculate the sum of squares of the input numbers? How would the time complexity change?"