Skip to content

perf: optimize hot paths and fix benchmark infrastructure#4410

Merged
matthew-dean merged 10 commits intoless:masterfrom
matthew-dean:dev/4.x-prep
Mar 9, 2026
Merged

perf: optimize hot paths and fix benchmark infrastructure#4410
matthew-dean merged 10 commits intoless:masterfrom
matthew-dean:dev/4.x-prep

Conversation

@matthew-dean
Copy link
Member

@matthew-dean matthew-dean commented Mar 9, 2026

Summary

  • Performance: Replace closures and forEach/map with for loops in hot paths (findMatch, Selector.eval, Ruleset.eval), yielding ~8% improvement on the 104KB benchmark (median 38.6ms → 36.4ms)
  • Benchmark fixes: Fix percentage() calls in benchmark .less files for v4's default parens-division math mode; add --math=always passthrough to benchmark runner for cross-version consistency
  • Benchmark infrastructure: Handle all v3.12+/v4.x build scenarios in run-historical.sh (pnpm for workspace protocol, fallback tsc, separate runtime dep install for broken monorepo npm installs); use last patch of each minor version

Benchmark results (104KB file, Apple M4 Pro)

Version Median (ms) Notes
v3.9.0 40.5 pre-regression baseline
v3.10.0 140.5 3.5x regression (Object.defineProperty)
v4.5.1 (released) 40.5 regression recovered
This PR 36.6 10% faster than v3.9

Test plan

  • All 205 tests pass (grunt test)
  • Benchmarked across v2.0–v4.5.1 with run-historical.sh
  • No behavioral changes — only constant-factor optimizations

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Enhanced Less percentage calculation parsing by clarifying division expressions in mathematical operations.
  • Performance

    • Optimized internal evaluation and iteration patterns in selector and ruleset processing for improved efficiency.

Wrap bare divisions inside percentage() calls in extra parens so
benchmarks work with v4's default parens-division math mode. Add
--math option passthrough to benchmark-runner.js and pass
--math=always in run-historical.sh for consistent cross-version results.
- Remove `extendVisitor` alias in findMatch, use `this` directly
- Replace IIFE closure for functionRegistry lookup in Ruleset.eval
  with inline loop

~5% improvement on main benchmark (median 38.6ms → 37.1ms)
- Selector.eval: replace map() closures with pre-allocated for loops
- Ruleset transformDeclaration: replace forEach with for loop
- extend-visitor visitRuleset: replace forEach with for loop, cache
  extend and pathCount to reduce repeated property access

Combined with previous commit: ~8% improvement on 104KB benchmark
(median 38.6ms → 36.4ms)
- Use pnpm for v4.3+ (workspace: protocol)
- Fallback tsc installation when npm can't install locally
- Install runtime deps separately when npm fails due to
  unpublished workspace packages (@less/test-import-module)
- Use last patch version of each minor release
- Skip v3.13.x (broken source: missing tree/util.js)
@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Mar 9, 2026
@coderabbitai
Copy link

coderabbitai bot commented Mar 9, 2026

Warning

Rate limit exceeded

@matthew-dean has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8bcc0971-2eaa-45cf-a9b2-0a2e46b049b9

📥 Commits

Reviewing files that changed from the base of the PR and between a1bdc97 and 749656d.

📒 Files selected for processing (5)
  • packages/less/benchmark/results/.gitignore
  • packages/less/benchmark/results/latest/macbook-pro_arm64.json
  • packages/less/benchmark/results/runs/2026-03-09T21-34-11Z_macbook-pro_arm64.json
  • packages/less/benchmark/results/runs/2026-03-09_macbook-pro_arm64.json
  • packages/less/benchmark/run-historical.sh
📝 Walkthrough

Walkthrough

The pull request refines the Less.js benchmark infrastructure and compiler internals. Changes include syntactic adjustments to Less files wrapping division expressions in parentheses, enhancement of the benchmark runner to accept command-line options, substantial updates to the historical benchmark script with TypeScript fallback mechanisms and workspace handling, consolidation of benchmark results, and refactoring of internal compiler evaluation patterns in ruleset, selector, and extend-visitor modules for explicit iteration and context handling.

Changes

Cohort / File(s) Summary
Benchmark Less Syntax Updates
benchmark-import-reference-target.less, benchmark-v39.less, benchmark.less
Added parentheses around division expressions in percentage calculations (e.g., percentage((@i/@n))) to clarify parsing without altering behavior.
Benchmark Infrastructure
benchmark-runner.js, run-historical.sh, results/latest/macbook-pro_arm64.json
Extended benchmark runner to parse command-line options (--key=value) and forward them to less.render; updated historical script with TypeScript fallback mechanism, workspace detection, expanded version list, and explicit --math=always flag; consolidated macbook-pro benchmark results JSON into single entry.
Compiler Evaluation Refactoring
src/less/tree/ruleset.js, src/less/tree/selector.js, src/less/visitors/extend-visitor.js
Refactored registry discovery from IIFE to explicit loop; replaced map-based array evaluation with guarded for loops in selector evaluation; refactored extend-visitor nested loops with explicit variable scoping and local iteration, removing unused context references.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Poem

🐰 With parentheses placed and options in hand,
The benchmark script runs throughout the land,
Old loops give way to explicit flows clear,
Compiler paths refined, optimization near!
✨ Registry discoveries, selectors align—
Less renders faster with each tweak so fine! 🏃‍♂️💨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: performance optimizations to hot code paths and fixes to the benchmark infrastructure, which align with the core changes across the entire PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

Median: 39.07ms → 34.32ms (~12% improvement)
Throughput: 2,495 KB/s → 2,828 KB/s
System: macbook-pro arm64
@dosubot dosubot bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Mar 9, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/less/benchmark/benchmark-runner.js (1)

13-19: Regex pattern only matches lowercase option names.

The pattern /^--([a-z-]+)=(.*)$/ won't match Less options with uppercase letters (e.g., --sourceMap=true, --strictMath=true). While this works for the current use case (--math=always), it may cause confusion if other options are needed later.

🔧 Suggested fix to support camelCase options
-  var optMatch = process.argv[ai].match(/^--([a-z-]+)=(.*)$/);
+  var optMatch = process.argv[ai].match(/^--([a-zA-Z-]+)=(.*)$/);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/less/benchmark/benchmark-runner.js` around lines 13 - 19, The
arg-parsing regex only allows lowercase option names, so update the parser in
the process.argv loop that builds extraOpts (the var extraOpts and optMatch
usage) to accept camelCase and digits; replace the pattern /^--([a-z-]+)=(.*)$/
with one that permits letters, digits, underscores and hyphens (e.g., use a
character class like [A-Za-z0-9_-] or \w plus hyphen) so options such as
--sourceMap=true and --strictMath=true are matched and stored in extraOpts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/less/benchmark/benchmark-runner.js`:
- Around line 13-19: The arg-parsing regex only allows lowercase option names,
so update the parser in the process.argv loop that builds extraOpts (the var
extraOpts and optMatch usage) to accept camelCase and digits; replace the
pattern /^--([a-z-]+)=(.*)$/ with one that permits letters, digits, underscores
and hyphens (e.g., use a character class like [A-Za-z0-9_-] or \w plus hyphen)
so options such as --sourceMap=true and --strictMath=true are matched and stored
in extraOpts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9d2fe84f-66bf-4a45-aef0-fe3c2a8b0a7f

📥 Commits

Reviewing files that changed from the base of the PR and between 7e48ad9 and a1bdc97.

📒 Files selected for processing (9)
  • packages/less/benchmark/benchmark-import-reference-target.less
  • packages/less/benchmark/benchmark-runner.js
  • packages/less/benchmark/benchmark-v39.less
  • packages/less/benchmark/benchmark.less
  • packages/less/benchmark/results/latest/macbook-pro_arm64.json
  • packages/less/benchmark/run-historical.sh
  • packages/less/src/less/tree/ruleset.js
  • packages/less/src/less/tree/selector.js
  • packages/less/src/less/visitors/extend-visitor.js

- Add historical benchmark data (v3.5–v4.2) to results/runs/
- Update latest/ with all versions including v4.5.0-dev optimized results
- Format JSON with 2-space indentation
- Update .gitignore to track runs/ (historical records belong in git)
Apple M4 Pro, arm64, Node v18/v20/v24

Key findings:
- v2.4-v2.5 fastest era (~31ms median on 104KB file)
- v3.10-v3.12 massive regression (3-5x slower, 126-185ms)
- v4.0 recovered to ~40ms
- v4.2 fastest v4.x (35.4ms)
- v4.5.1 current master: 42.2ms
@dosubot dosubot bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Mar 9, 2026
Reduced from 23 to 15 versions based on full benchmark data.
Dropped versions with <5% difference from their predecessor:
- v2.1 (broken), v2.5, v2.7 (plateau with v2.4/v2.6)
- v3.6–v3.9 (all within 1ms, flat ~41ms)
- v4.1 (identical to v4.0)

The full set can still be run with --versions flag.
@matthew-dean matthew-dean merged commit 6f82d19 into less:master Mar 9, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant