Variable scope (lexical scoping) in R Programming - Time & Space Complexity
We want to see how the time to run code changes when using variables inside and outside functions.
How does the place where a variable is defined affect how long the program takes?
Analyze the time complexity of the following code snippet.
outer_function <- function(n) {
x <- 0
inner_function <- function() {
for (i in 1:n) {
x <<- x + i
}
return(x)
}
inner_function()
}
outer_function(1000)
This code defines a function inside another function and uses a variable from the outer function inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside
inner_functionthat runs from 1 to n. - How many times: It runs exactly n times, where n is the input size.
Each time n gets bigger, the loop runs more times, so the work grows in a straight line with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
Pattern observation: The number of steps grows directly with the input size.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input number n grows.
[X] Wrong: "Using a variable from outside the inner function makes the code slower or more complex."
[OK] Correct: The variable access is quick because R uses lexical scoping, so it finds the variable without extra loops or work.
Understanding how variable scope affects performance helps you write clear and efficient code, a skill valued in many programming tasks.
"What if the inner function created its own local variable instead of using the outer one? How would the time complexity change?"