1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add OpenStruct Has Bad Performance Characteristics as a Ruby TIL

This commit is contained in:
jbranchaud
2025-02-17 15:32:15 -06:00
parent 14e6635383
commit 6ff8f19d08
2 changed files with 34 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1592 TILs and counting..._
_1593 TILs and counting..._
See some of the other learning resources I work on:
- [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators)
@@ -1319,6 +1319,7 @@ See some of the other learning resources I work on:
- [Named Regex Captures Are Assigned To Variables](ruby/named-regex-captures-are-assigned-to-variables.md)
- [Navigate Back In The Browser With Capybara](ruby/navigate-back-in-the-browser-with-capybara.md)
- [Next And Previous Floats](ruby/next-and-previous-floats.md)
- [OpenStruct Has Bad Performance Characteristics](ruby/open-struct-has-bad-performance-characteristics.md)
- [Or Operator Precedence](ruby/or-operator-precedence.md)
- [Output Bytecode For A Ruby Program](ruby/output-bytecode-for-a-ruby-program.md)
- [Override The Initial Sequence Value](ruby/override-the-initial-sequence-value.md)

View File

@@ -0,0 +1,32 @@
# OpenStruct Has Bad Performance Characteristics
The Ruby docs for `OpenStruct` have a [_Caveats_
section](https://ruby-doc.org/3.4.1/stdlibs/ostruct/OpenStruct.html#class-OpenStruct-label-Caveats)
that warns about the poor performance characteristics of `OpenStruct` relative
to `Struct` and `Hash`.
> This should be a consideration if there is a concern about the performance of
> the objects that are created, as there is much more overhead in the setting
> of these properties compared to using a Hash or a Struct. Creating an open
> struct from a small Hash and accessing a few of the entries can be 200 times
> slower than accessing the hash directly.
This doesn't mean don't use `OpenStruct`, but do be aware of if you are using
it in a hot path or if you are allocating and processing tons of them.
If you turn on _Performance Warnings_ in Ruby, you'll see a warning message
when allocating an `OpenStruct`.
```ruby
> require 'ostruct'
=> true
> os1 = OpenStruct.new
=> #<OpenStruct>
> Warning[:performance] = true
=> true
> os2 = OpenStruct.new
(irb):6: warning: OpenStruct use is discouraged for performance reasons
=> #<OpenStruct>
```
[source](https://www.reddit.com/r/ruby/comments/1d54mwl/comment/l6jgn59/)