0
0
SASSmarkup~8 mins

@for loop (through vs to) in SASS - Performance Comparison

Choose your learning style9 modes available
Performance: @for loop (through vs to)
MEDIUM IMPACT
This affects CSS preprocessing time and the size of the generated CSS file, impacting page load speed.
Generating repeated CSS classes with a loop
SASS
@for $i from 1 to 10 {
  .item-#{$i} {
    width: 10px * $i;
  }
}
The 'to' keyword excludes the last number, generating fewer CSS rules and reducing file size.
📈 Performance GainSaves 1 CSS rule, reducing CSS size and improving LCP marginally.
Generating repeated CSS classes with a loop
SASS
@for $i from 1 through 10 {
  .item-#{$i} {
    width: 10px * $i;
  }
}
The 'through' keyword includes the last number, causing one extra iteration which may generate unnecessary CSS rules.
📉 Performance CostAdds 1 extra CSS rule, increasing CSS file size and slightly delaying LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
@for ... through (1 through 10)0 (CSS only)0Low[!] OK
@for ... to (1 to 10)0 (CSS only)0Lower[OK] Good
Rendering Pipeline
Sass loops run during CSS preprocessing, affecting the size of the CSS file sent to the browser. Larger CSS files increase download and parse time, impacting the Critical Rendering Path.
Network
CSS Parsing
Style Calculation
⚠️ BottleneckNetwork and CSS Parsing due to larger CSS file size
Core Web Vital Affected
LCP
This affects CSS preprocessing time and the size of the generated CSS file, impacting page load speed.
Optimization Tips
1Use '@for ... to' to avoid generating unnecessary CSS rules.
2Smaller CSS files improve Largest Contentful Paint (LCP).
3Avoid extra iterations in loops to keep CSS size minimal.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main difference between '@for ... through' and '@for ... to' in Sass loops?
ABoth generate the same number of iterations
B'to' includes the last number, 'through' excludes it
C'through' includes the last number, 'to' excludes it
D'through' is faster to compile than 'to'
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by CSS file, and compare file sizes generated by 'through' vs 'to' loops.
What to look for: Look for smaller CSS file size and faster download time indicating better performance.