0
0
SASSmarkup~8 mins

Recursive mixins in SASS - Performance & Optimization

Choose your learning style9 modes available
Performance: Recursive mixins
MEDIUM IMPACT
This affects CSS compilation time and the size of the generated CSS, impacting page load speed and rendering performance.
Generating nested styles with recursion in Sass
SASS
@mixin recursive-good($n) {
  @for $i from 1 through $n {
    .level-#{$i} {
      color: red;
    }
  }
}

@include recursive-good(10);
Using a loop instead of recursion reduces compiler overhead and generates flat CSS, improving compile time and output size.
📈 Performance GainSingle loop compile, smaller CSS output, faster page load.
Generating nested styles with recursion in Sass
SASS
@mixin recursive-bad($n) {
  @if $n > 0 {
    .level-#{$n} {
      color: red;
      @include recursive-bad($n - 1);
    }
  }
}

@include recursive-bad(10);
This recursive mixin generates deeply nested selectors and repeated styles, increasing CSS size and compile time.
📉 Performance CostTriggers multiple nested loops in compiler, increasing compile time linearly with $n; generates large CSS increasing page load.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Recursive mixin with deep nestingN/A (CSS only)N/AHigh due to complex selectors[X] Bad
Loop-based mixin generating flat CSSN/A (CSS only)N/ALow due to simple selectors[OK] Good
Rendering Pipeline
Recursive mixins affect the CSS compilation stage before the browser rendering pipeline. Large or deeply nested CSS increases CSS file size, which delays Style Calculation and Layout stages in the browser.
Style Calculation
Layout
Paint
⚠️ BottleneckStyle Calculation due to large CSS and complex selectors
Core Web Vital Affected
LCP
This affects CSS compilation time and the size of the generated CSS, impacting page load speed and rendering performance.
Optimization Tips
1Avoid deep recursion in Sass mixins to prevent large CSS output.
2Prefer loops (@for, @each) over recursion for generating repetitive styles.
3Keep generated CSS selectors simple to reduce browser style calculation time.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance drawback of using recursive mixins in Sass?
AThey reduce CSS specificity causing style conflicts.
BThey can generate very large CSS files increasing page load time.
CThey prevent CSS from being cached by browsers.
DThey cause JavaScript to run slower on the page.
DevTools: Network and Performance panels
How to check: Use Network panel to check CSS file size and load time; use Performance panel to record page load and see Style Calculation duration.
What to look for: Large CSS files and long Style Calculation times indicate inefficient recursive mixins.