0
0
Gitdevops~5 mins

pre-commit hook in Git - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: pre-commit hook
O(n)
Understanding Time Complexity

We want to understand how the time taken by a pre-commit hook changes as the project size grows.

Specifically, how does running checks before each commit scale with the number of files or changes?

Scenario Under Consideration

Analyze the time complexity of this simple pre-commit hook script.

#!/bin/sh
# Run lint on all staged files
files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.js$')

for file in $files; do
  eslint "$file"
done

This hook runs a linter on each staged JavaScript file before allowing a commit.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over each staged JavaScript file to run eslint.
  • How many times: Once for each staged .js file in the commit.
How Execution Grows With Input

As the number of staged JavaScript files increases, the number of eslint runs grows linearly.

Input Size (n files)Approx. Operations (eslint runs)
1010
100100
10001000

Pattern observation: The work grows directly in proportion to the number of files checked.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the pre-commit hook grows linearly with the number of staged files.

Common Mistake

[X] Wrong: "The pre-commit hook runs in constant time regardless of files."

[OK] Correct: Each file adds work because the hook runs eslint on every staged file, so more files mean more time.

Interview Connect

Understanding how pre-commit hooks scale helps you write efficient checks that keep your workflow smooth as projects grow.

Self-Check

"What if the hook ran eslint once on all files together instead of one by one? How would the time complexity change?"