0
0
SASSmarkup~8 mins

@each loop over maps in SASS - Performance & Optimization

Choose your learning style9 modes available
Performance: @each loop over maps
MEDIUM IMPACT
This affects CSS generation time and the final CSS file size, impacting page load speed and render time.
Generating CSS classes from a map of colors
SASS
$colors: (red: #f00, green: #0f0, blue: #00f);
@each $name, $hex in $colors {
  .text-#{$name} {
    color: $hex;
  }
  .bg-#{$name} {
    background-color: $hex;
  }
}
Single @each loop over map reduces iterations and generates concise CSS.
📈 Performance GainSingle iteration; smaller CSS file; faster compilation.
Generating CSS classes from a map of colors
SASS
@each $color in (red, green, blue) {
  .text-#{$color} {
    color: $color;
  }
}

@each $color in (red, green, blue) {
  .bg-#{$color} {
    background-color: $color;
  }
}
Repeating @each loops separately for related styles causes duplicated iteration and larger CSS output.
📉 Performance CostIncreases CSS file size and compilation time; triggers multiple passes over the same data.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Separate @each loops over listsN/A (build time)N/ALarger CSS size delays style application[X] Bad
Single @each loop over mapN/A (build time)N/ASmaller CSS size loads faster[OK] Good
Rendering Pipeline
Sass @each loops run at build time, generating CSS before the browser loads the page. Efficient loops produce smaller CSS files, reducing network load and improving initial render.
Network Load
Style Calculation
Layout
⚠️ BottleneckNetwork Load due to CSS file size
Core Web Vital Affected
LCP
This affects CSS generation time and the final CSS file size, impacting page load speed and render time.
Optimization Tips
1Use a single @each loop over maps to generate related CSS rules together.
2Avoid repeating @each loops over the same data to reduce CSS size.
3Check CSS file size in DevTools Network panel to ensure efficient output.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance benefit of using a single @each loop over a map in Sass?
AIncreases DOM nodes created by the browser
BTriggers more reflows during page load
CReduces CSS file size by avoiding repeated loops
DBlocks JavaScript execution on the page
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, filter by CSS files, and check file size.
What to look for: Smaller CSS file size indicates efficient @each loops; large CSS files suggest duplication.