0
0
SASSmarkup~8 mins

@each loop over lists in SASS - Performance & Optimization

Choose your learning style9 modes available
Performance: @each loop over lists
MEDIUM IMPACT
This affects CSS generation time and the final CSS file size, impacting page load speed and rendering.
Generating repeated CSS rules for multiple colors
SASS
@each $color in (red, blue, green) {
  .btn-#{$color} {
    background-color: $color;
  }
}

/* Use CSS variables or utility classes for other colors to reduce duplication */
Limits the number of generated CSS rules, reducing CSS size and compile time.
📈 Performance GainSaves several kb in CSS bundle; faster compile time.
Generating repeated CSS rules for multiple colors
SASS
@each $color in (red, blue, green, yellow, orange, purple, pink, brown, black, white) {
  .btn-#{$color} {
    background-color: $color;
  }
}
Loops over a large list generate many CSS rules, increasing CSS file size and compile time.
📉 Performance CostAdds ~1kb per item to CSS bundle; increases compile time linearly with list size.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Large @each loop generating many classes0 (compile time only)0High due to large CSS[X] Bad
Small @each loop with few classes0 (compile time only)0Low CSS size, faster paint[OK] Good
Rendering Pipeline
The @each loop runs at compile time, generating CSS rules that the browser later parses and applies during style calculation and paint.
CSS Parsing
Style Calculation
Paint
⚠️ BottleneckCSS Parsing and Style Calculation due to large generated CSS
Core Web Vital Affected
LCP
This affects CSS generation time and the final CSS file size, impacting page load speed and rendering.
Optimization Tips
1Limit the number of items in @each loops to reduce CSS size.
2Use CSS variables or utility classes to avoid generating many repetitive rules.
3Check generated CSS size in DevTools Network panel to monitor impact.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance impact of using a large @each loop over lists in Sass?
AIncreases DOM nodes count
BSlows down JavaScript execution
CIncreases CSS file size and compile time
DCauses layout shifts during page load
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by CSS files, and check the size of the generated CSS file.
What to look for: Large CSS file size indicates many generated rules; this can slow page load and style application.