Skip to content

#89: faster Dir.glob, shared Regexp translations, tighter count/delete/squeeze loops - #175

Merged
Largo merged 3 commits into
masterfrom
claude/issue-89-more
Nov 9, 2026
Merged

Largo merged 3 commits into
masterfrom
claude/issue-89-more

Conversation

@Largo

@Largo Largo commented Nov 9, 2026 •

Copy link
Copy Markdown
Owner

Part of #89. Three of its unticked items that #171 did not cover, one commit each. Behaviour is unchanged; the expected outputs of the new tests are CRuby 4.0's.

#89 items this addresses

  • Dir.glob is still ~5–8× slower than CRuby (Strings and regexps). The per-entry existence checks are gone without changing how broken symlinks are handled.
  • Regexp.new and interpolated regex literals are ~4× and ~1.8× slower than CRuby. There is now a shared regex cache, and tier-up still works per instance.
  • String#count, #delete and #squeeze: the remaining per-character overhead. ljust/center with a 10000-character result measure the same as CRuby now (14 µs both), so nothing was changed there.

All numbers are main-thread CPU time (/proc/thread-self/stat), from Release net8.0 builds of fork/master (8cc413b) and of this branch, run interleaved A B B A. Each figure is the best of 3 rounds of at least 300 ms.

1. Dir.glob (8abce10)

Every matched entry used to be checked again:

  • DirectoryExists + FileExists for a last segment;
  • DirectoryExists before walking into it;
  • a DirectoryInfo.LinkTarget check under **.

**/x also listed every directory twice.

When the PAL is the real file system (it does not override FileExists, DirectoryExists or GetFileSystemEntries), the listing now comes from FileSystemEnumerable, and each entry keeps IsDirectory. That flag follows a symlink, as DirectoryExists does.

  • A listed last segment is reported with no further check.
  • A non-directory is not walked into.
  • The symlink check runs for directories only.
  • The last listing is reused.

Broken symlinks: a dangling link is still reported. File.Exists answered true for one, and MRI lists it too. */ and */* still go through links to directories, and ** still does not.

Windows: a reparse point keeps the old checks, because its Directory attribute says nothing about its target.

Host PALs: a PAL with its own file system is still asked through its own methods. Dir_GlobVirtualPal1 covers this with a PAL that lists an entry its FileExists denies.

20 dirs × 50 files master branch CRuby
Dir.glob("*/*.rb") (520 hits) 4.9–5.4 ms 0.65 ms 0.50 ms
Dir.glob("**/*.txt") (1000 hits) 19.2–19.6 ms 1.6–1.7 ms 0.96 ms
Dir.glob("**/*") 22.9–23.8 ms 1.6–1.7 ms 0.91 ms
Dir.glob("d1/*") 254–260 µs 47 µs 26 µs

2. Regexp.new (70ed244)

The cache holds the last 256 patterns. It is keyed on the translation's input, the options and the timeout, and it gives back the same CLR Regex (immutable and thread-safe) together with its \G flag. Failed patterns are not cached, so a bad one still raises every time.

Tier-up is still per instance: each Regexp counts its own matches. The one that compiles puts its compiled regex in the cache, so Regexps of that pattern made afterwards start compiled (Regex_SharedTranslation2).

master branch CRuby
Regexp.new("foo(\\d+)bar[a-z]*") 6.5–9.8 µs 0.31–0.36 µs 4.1 µs
/#{x}\d+(?:y|z)/ 2.7–3.5 µs 0.48 µs 3.3 µs
"zabc12y" =~ /#{x}\d+(?:y|z)/ 4.3–4.7 µs 0.89 µs 4.0 µs

3. String#count / #delete / #squeeze (ca897b1)

The loops from #171 were inlined into large methods. There, RyuJIT kept the loop index on the stack, so each character waited for a store and a reload: about 2 ns per character, three times a standalone loop (checked with DOTNET_JitDisasm and perf). The changes:

  • The loops are NoInlining.
  • The non-ASCII test is out of line, and is skipped when no selector can pick a non-ASCII character.
  • A one-character ASCII set uses the vectorized MemoryExtensions.Count.
  • From 256 characters on, ASCII characters are looked up in a 128-byte table, built once per set.
  • #delete and #squeeze store every character and advance past it unless it is dropped, instead of branching.
1140 ASCII chars master branch CRuby
count("lo") 1.6 µs 1.2 µs 1.2 µs
count("l") 1.7 µs 0.45 µs 0.46 µs
count("a-y") 1.7 µs 1.2 µs 1.3 µs
delete("l") 3.3 µs 2.0–2.4 µs 2.0 µs
delete("a-m") 3.0 µs 2.2–2.4 µs 2.1 µs
squeeze 3.3 µs 2.3–2.4 µs 1.3 µs
squeeze("l") 3.6 µs 3.3 µs 1.2 µs

11-character strings are unchanged (0.2–0.45 µs). squeeze with a set is still ~2.8× CRuby. What remains there is mostly the call path and the result allocation, not the loop.

Verification

  • IronRuby.Tests, Debug net8.0, full run: 0 failures. Both TFMs build. New tests:
    • Dir_GlobListing1
    • Dir_GlobVirtualPal1
    • Regex_SharedTranslation1, Regex_SharedTranslation2
    • String_CountDeleteSqueeze3
  • ruby/spec at CI's SPEC_REF, Release net8.0, master against this branch: core/string, core/file, core/dir (without chroot_spec, which hangs as root on master too), core/regexp, core/matchdata, library/pathname.
    • Same result on both: 0 failures. The same 4 errors are pre-existing: String.try_convert, and Regexp.compile/new/try_convert with a bad #to_str/#to_regexp.
    • In one master run, the File.socket? specs errored twice, from the two runs sharing a socket path.
  • Differential scripts, branch against master against CRuby 4.0:
    • Glob: 37 patterns, with dangling links, links to files and directories, .., base: and FNM_DOTMATCH.
    • Strings: 600 random strings × 8 count/delete/squeeze/! calls, with multibyte, astral, binary and negated or multiple sets.
    • Regexps: ~840 lines of Regexp.new/match/scan/gsub over options, named groups, \G, timeouts, errors and hot loops.
    • The branch output is identical to master's in every case.

Not done

Found, not changed (already on master; CRuby 4.0.9 differs)

  • Glob results are lexically normalized by .NET:
    • Dir["d1/*/../f1.rb"] also reports d1/link/../f1.rb through a symlinked directory.
    • Dir["d1/f1.rb/../f2.rb"] matches through a file.
  • Dir["**/*"] lists a directory's matches before descending into its subdirectories. MRI interleaves them per entry (a/sub/z.rb before a/x.rb). With FNM_DOTMATCH, "." comes last instead of first.
  • A symlink loop under a wildcard is skipped silently; MRI raises Errno::ELOOP.
  • s.count("^\0-\x7f", "あ") is 0 in MRI, which looks like an MRI quirk with a negated first set and a multibyte set. IronRuby counts the あ.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • File globbing now uses directory listings more efficiently, with improved handling of sorted results, recursive patterns, and custom filesystem providers.
    • String counting, deletion, and squeezing are more efficient for common ASCII and single-character cases.
    • Compatible regular expressions can share translated and compiled representations, reducing repeated work while preserving behavior across differing options and timeouts.
  • Tests
    • Expanded coverage for globbing, string operations, and regular expression reuse.

Largo and others added 3 commits November 9, 2026 15:09
)

Every matched entry used to be asked about again: DirectoryExists plus
FileExists for a last segment, DirectoryExists before walking into it, a
DirectoryInfo/LinkTarget check under "**", and "**/x" listed every
directory twice. On the real file system (a PAL that does not override
FileExists, DirectoryExists or GetFileSystemEntries) the listing now
comes from FileSystemEnumerable and keeps readdir's answer of whether an
entry is a directory (following a symbolic link, as DirectoryExists
does). A listed last segment is reported without another check, a
non-directory is not walked into, the symlink check runs for directories
only, and the last listing is reused.

Behaviour is unchanged: a dangling link is still reported (FileExists
said true for one, and MRI lists it), "*/" and "**" still see links to
directories, sorting is per directory as before. On Windows a reparse
point keeps the old checks, since its Directory attribute says nothing
about its target. A host PAL with its own file system is still asked
through its own methods.

Release net8.0, main-thread CPU time, a 20-directory tree:
  Dir.glob("*/*.rb")    ~5.1 ms  -> 0.65 ms (CRuby 0.50)
  Dir.glob("**/*.txt") ~19.4 ms  -> 1.65 ms (CRuby 0.96)
  Dir.glob("**/*")     ~23.3 ms  -> 1.65 ms (CRuby 0.91)
  Dir.glob("d1/*")      ~257 us  ->   47 us (CRuby 26)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…#89)

Regexp.new and every evaluation of an interpolated literal (/#{x}/)
translated the pattern and had .NET parse the result. A cache of the
last 256 patterns, keyed on the translation's input, the options and
the timeout, now hands out the same CLR Regex (immutable and
thread-safe) together with its \G flag. Failed patterns are not cached,
so a bad one still raises every time.

Tier-up stays per instance: each Regexp counts its own matches, and the
one that compiles its regex puts the compiled one in the cache, so
Regexps of that pattern made afterwards start out compiled.

Release net8.0, main-thread CPU time:
  Regexp.new("foo(\\d+)bar[a-z]*")   ~6.5-9.8 us -> 0.33 us (CRuby 4.1)
  /#{x}\d+(?:y|z)/                   ~2.7-3.5 us -> 0.48 us (CRuby 3.3)
  "zabc12y" =~ /#{x}\d+(?:y|z)/      ~4.3-4.7 us -> 0.89 us (CRuby 4.0)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The loops from #171 were inlined into InternalCount and friends, large
methods, where RyuJIT kept the loop index on the stack: every character
waited for a store and a reload (about 2 ns a character, 3x a standalone
loop). They are now NoInlining methods, with the non-ASCII test out of
line, and:

- a set of one ASCII character ("l") is counted with the vectorized
  MemoryExtensions.Count;
- when no selector can pick a non-ASCII character, those skip the test;
- from 256 characters on, ASCII characters are looked up in a 128-byte
  table built once per set (short strings keep the mask test, so they
  pay nothing for it);
- #delete and #squeeze store each character and advance past it unless
  it is dropped, instead of branching on every one.

Release net8.0, main-thread CPU time, 1140 ASCII characters:
  count("lo")    ~1.6 us -> 1.2 us   (CRuby 1.2)
  count("l")     ~1.7 us -> 0.45 us  (CRuby 0.46)
  count("a-y")   ~1.7 us -> 1.2 us   (CRuby 1.3)
  delete("l")    ~3.3 us -> 2.0-2.4 us (CRuby 2.0)
  delete("a-m")  ~3.0 us -> 2.2-2.4 us (CRuby 2.1)
  squeeze        ~3.3 us -> 2.3-2.4 us (CRuby 1.3)
  squeeze("l")   ~3.6 us -> 3.3 us   (CRuby 1.2)
11-character strings are unchanged (0.2-0.45 us).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The changes optimize string counting, deletion, and squeezing; update glob directory enumeration and traversal; and add a shared cache for translated CLR regexes. Tests cover the updated string and glob behavior, regex reuse, and compilation tiering.

Changes: String operation updates

Layer / File(s) Summary
Character selection and squeeze paths
Src/Libraries/Builtins/MutableStringOps.cs, Src/IronRuby.Tests/Runtime/StringTests.cs, Src/IronRuby.Tests/RubyTests.cs
Character selector metadata supports ASCII-oriented counting and copying paths. Squeeze span copying uses dedicated character and byte methods. Tests cover ASCII, UTF-8, and binary strings. The test registry includes the new test.

Glob listing updates

Layer / File(s) Summary
Directory listing and glob traversal
Src/Ruby/Builtins/Glob.cs, Src/IronRuby.Tests/Runtime/IoTests.cs, Src/IronRuby.Tests/RubyTests.cs
Glob traversal uses cached directory listings and entry-kind information when available. Tests cover real filesystem and virtual PAL results. The test registry includes both new tests.

Shared regex translation

Layer / File(s) Summary
Shared translation and compilation promotion
Src/Ruby/Builtins/RubyRegex.cs, Src/IronRuby.Tests/Runtime/RegexTests.cs, Src/IronRuby.Tests/RubyTests.cs
Translated regexes are shared by pattern, options, and timeout. Cache entries preserve \G metadata and can be updated when an instance compiles. Tests cover reuse, separation, and compilation tiering.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related issues

  • Largo/ironruby#89 — The changes optimize Dir.glob, regex translation, and String#count, #delete, and #squeeze, which are performance areas identified by the issue.

Suggested reviewers: claude

Merge Risk: Minimal · up to ca897

This PR speeds up Dir.glob, regexp translation, and String#count/#delete/#squeeze while reportedly preserving behavior. No concrete defect was found in the supplied changes, and new tests cover the main paths. It looks ready to merge, subject to the normal CI run.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names three changes: faster Dir.glob, shared Regexp translations, and tighter String count/delete/squeeze loops. The raw summary and PR objectives cover all three. The title is a single sent…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names three changes: faster Dir.glob, shared Regexp translations, and tighter String count/delete/squeeze loops. The raw summary and PR objectives cover all three. The title is a single sentence, but it lists three separate items and omits the wider scope, such as the new tests. It also begins with a '#89:' issue prefix that does not describe the change itself. The title is accurate and specific enough to pass.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 8cc413b and ca897b1.

Files selected for processing: 7

  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/IoTests.cs
  • Src/IronRuby.Tests/Runtime/RegexTests.cs
  • Src/IronRuby.Tests/Runtime/StringTests.cs
  • Src/Libraries/Builtins/MutableStringOps.cs
  • Src/Ruby/Builtins/Glob.cs
  • Src/Ruby/Builtins/RubyRegex.cs

Included review availability: This review used your included allowance. 0 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant