Function declaration in Go - Time & Space Complexity
When we declare a function, we want to know how its execution time changes as we use it with different inputs.
Here, we ask: does just declaring a function affect how long the program runs?
Analyze the time complexity of the following code snippet.
func greet(name string) string {
return "Hello, " + name
}
func main() {
message := greet("Alice")
println(message)
}
This code declares a simple function that returns a greeting message and then calls it once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single function call with string concatenation.
- How many times: The function is called once; no loops or recursion.
Execution time grows very little because the function runs once and does a simple string join.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 call with small string work |
| 100 | Still 1 call, slightly more string work |
| 1000 | Still 1 call, more string joining but no loops |
Pattern observation: The time depends on the size of the input string but the function runs only once, so growth is very small.
Time Complexity: O(n)
This means the time grows linearly with the length of the input string, but only because of string joining, not because of repeated calls.
[X] Wrong: "Declaring a function makes the program slower as input grows."
[OK] Correct: Declaring a function itself does not run code or slow the program; only calling it does, and how often it runs matters more.
Understanding that function declaration alone does not affect time helps you focus on what really matters: how many times and how the function runs.
"What if the function greet was called inside a loop running n times? How would the time complexity change?"