Skip to content

Commit

Permalink
Freeze absolute paths to reduce allocations on file operations
Browse files Browse the repository at this point in the history
Most of the `File` methods cast the paths it receives with `FilePathValue`
which ultimately delegate to `rb_new_str_frozen`.

`rb_new_str_frozen` could be experessed as `str.frozen? ? str : str.dup`.

So by freezing the paths passed to the various `File.` methods, we
save at least one useless allocation each time, unless the string encoding
is incompatible with the file system.

```
s = __FILE__
alloc = GC.stat[:total_allocated_objects]
File.realpath(s)
p GC.stat[:total_allocated_objects] - alloc # => 3

s = __FILE__.freeze
alloc = GC.stat[:total_allocated_objects]
File.realpath(s)
p GC.stat[:total_allocated_objects] - alloc # => 2
```
  • Loading branch information
byroot committed Jun 28, 2020
1 parent 7084c7e commit 0a68f87
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/zeitwerk/loader.rb
Expand Up @@ -616,7 +616,7 @@ def set_autoload(parent, cname, abspath)
# $LOADED_FEATURES stores real paths since Ruby 2.4.4. We set and save the
# real path to be able to delete it from $LOADED_FEATURES on unload, and to
# be able to do a lookup later in Kernel#require for manual require calls.
realpath = File.realpath(abspath)
realpath = File.realpath(abspath).freeze
parent.autoload(cname, realpath)
if logger
if ruby?(realpath)
Expand Down Expand Up @@ -719,7 +719,7 @@ def cpath(parent, cname)
def ls(dir)
Dir.foreach(dir) do |basename|
next if basename.start_with?(".")
abspath = File.join(dir, basename)
abspath = File.join(dir, basename).freeze
yield basename, abspath unless ignored_paths.member?(abspath)
end
end
Expand Down

0 comments on commit 0a68f87

Please sign in to comment.