Commit cfec60d
committed
dir.c: cache and revalidate working directory
`rb_dir_getwd_ospath()` is called quite frequently, but
the overwhelming majority of the time, the current directory
didn't change.
We can also assume that most of the time, `PATH_MAX` is enough
for `getcwd`, hence we can first attempt to use a small stack
buffer rather than always allocate on the heap.
This way we can keep the last `pwd` and revalidate it with no
allocation.
On macOS syscalls are fairly slow, so the gain isn't very large.
macOS:
```
compare-ruby: ruby 4.1.0dev (2026-04-09T05:19:02Z master c091c18) +PRISM [arm64-darwin25]
built-ruby: ruby 4.1.0dev (2026-04-09T06:37:20Z get-cwd-cache ea02126d79) +PRISM [arm64-darwin25]
```
| |compare-ruby|built-ruby|
|:--------|-----------:|---------:|
|Dir.pwd | 105.183k| 113.420k|
| | -| 1.08x|
```
Linux (inside virtualized Docker)
```
compare-ruby: ruby 4.1.0dev (2026-04-07T08:26:25Z master fcd2100) +PRISM [aarch64-linux]
built-ruby: ruby 4.1.0dev (2026-04-09T06:38:09Z get-cwd-cache 6774af9) +PRISM [aarch64-linux]
```
| |compare-ruby|built-ruby|
|:--------|-----------:|---------:|
|Dir.pwd | 4.157M| 5.541M|
| | -| 1.33x|1 parent b154cfa commit cfec60d
2 files changed
+31
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1585 | 1585 | | |
1586 | 1586 | | |
1587 | 1587 | | |
| 1588 | + | |
| 1589 | + | |
1588 | 1590 | | |
1589 | 1591 | | |
1590 | 1592 | | |
| |||
1604 | 1606 | | |
1605 | 1607 | | |
1606 | 1608 | | |
1607 | | - | |
1608 | | - | |
| 1609 | + | |
| 1610 | + | |
1609 | 1611 | | |
1610 | 1612 | | |
1611 | 1613 | | |
1612 | 1614 | | |
| 1615 | + | |
| 1616 | + | |
| 1617 | + | |
| 1618 | + | |
| 1619 | + | |
| 1620 | + | |
| 1621 | + | |
| 1622 | + | |
| 1623 | + | |
| 1624 | + | |
| 1625 | + | |
| 1626 | + | |
| 1627 | + | |
| 1628 | + | |
| 1629 | + | |
| 1630 | + | |
| 1631 | + | |
| 1632 | + | |
| 1633 | + | |
| 1634 | + | |
| 1635 | + | |
| 1636 | + | |
| 1637 | + | |
1613 | 1638 | | |
1614 | 1639 | | |
1615 | 1640 | | |
1616 | 1641 | | |
1617 | 1642 | | |
1618 | 1643 | | |
1619 | 1644 | | |
1620 | | - | |
| 1645 | + | |
1621 | 1646 | | |
1622 | 1647 | | |
1623 | 1648 | | |
| |||
4008 | 4033 | | |
4009 | 4034 | | |
4010 | 4035 | | |
| 4036 | + | |
4011 | 4037 | | |
4012 | 4038 | | |
4013 | 4039 | | |
| |||
0 commit comments