Stage conditions with when directive in Jenkins - Time & Space Complexity
We want to understand how the time it takes to run a Jenkins pipeline changes when using the when directive in stages.
Specifically, we ask: How does adding conditions affect the number of operations Jenkins performs?
Analyze the time complexity of the following Jenkins pipeline snippet using when conditions.
pipeline {
agent any
stages {
stage('Build') {
when {
branch 'main'
}
steps {
echo 'Building...'
}
}
stage('Test') {
when {
expression { return params.RUN_TESTS }
}
steps {
echo 'Testing...'
}
}
}
}
This pipeline runs stages only if their when conditions are true, controlling execution flow.
Look for repeated checks or evaluations in the pipeline.
- Primary operation: Evaluating
whenconditions before each stage runs. - How many times: Once per stage, so the number of stages determines how many condition checks happen.
As the number of stages increases, Jenkins checks each stage's when condition once.
| Input Size (n = number of stages) | Approx. Operations (condition checks) |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of condition checks grows directly with the number of stages.
Time Complexity: O(n)
This means the time to evaluate stage conditions grows linearly with the number of stages in the pipeline.
[X] Wrong: "Adding more when conditions won't affect pipeline run time much because they are simple checks."
[OK] Correct: Each when condition is checked once per stage, so more stages mean more checks, increasing total time linearly.
Understanding how conditional checks scale helps you design efficient pipelines and shows you can reason about execution costs in automation tasks.
What if we added nested when conditions inside stages? How would the time complexity change?