0
0
Jenkinsdevops~5 mins

Stage conditions with when directive in Jenkins - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Stage conditions with when directive
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

Look for repeated checks or evaluations in the pipeline.

  • Primary operation: Evaluating when conditions before each stage runs.
  • How many times: Once per stage, so the number of stages determines how many condition checks happen.
How Execution Grows With Input

As the number of stages increases, Jenkins checks each stage's when condition once.

Input Size (n = number of stages)Approx. Operations (condition checks)
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of condition checks grows directly with the number of stages.

Final Time Complexity

Time Complexity: O(n)

This means the time to evaluate stage conditions grows linearly with the number of stages in the pipeline.

Common Mistake

[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.

Interview Connect

Understanding how conditional checks scale helps you design efficient pipelines and shows you can reason about execution costs in automation tasks.

Self-Check

What if we added nested when conditions inside stages? How would the time complexity change?