"type-guessr" needed to collect info from project code at
startup and it was slow.
So, I profiled and…
Background
4
Slide 5
Slide 5 text
ko1: "Class.new is faster than them"
shia: "…!?!?"
Background
5
Slide 6
Slide 6 text
Target: Initialization speed
- Data.define, Struct, Class
- kwargs, positional args
- 1 ivar, 8 ivars
Ruby 4.0.1 / linux / no YJIT
So, benchmark it
6
Slide 7
Slide 7 text
Result
7
1 field
8 fields
Slide 8
Slide 8 text
- Class.new > Struct.new >> Data.define.new
- kwargs are slow
- more ivars, more slower
Observation
8
Slide 9
Slide 9 text
Observation
9
8 fields
- Class.new > Struct.new >> Data.define.new
- kwargs are slow
- more ivars, more slower
Note: Class.new outperforms with YJIT
Slide 10
Slide 10 text
See perf results
10
"perf record -g --call-graph dwarf"
Ruby 4.0.1 / linux / no YJIT / ivar 1 field
Slide 11
Slide 11 text
See perf results
11
Slide 12
Slide 12 text
See perf results
12
Slide 13
Slide 13 text
See perf results
13
Slide 14
Slide 14 text
See perf results
14
Slide 15
Slide 15 text
See perf results
15
Slide 16
Slide 16 text
- Is kwargs initialization optimized?
- Create Hash for kwargs on initialization or not
- Is ivar access optimized?
- Byte code caching with object shape applied or not
- Does the object need to be frozen?
Why??
16
Slide 17
Slide 17 text
shia: "I found it really is.."
ko1: "We optimize what people use most, so yeah"
shia: "That's absolutely true😂"
After talk
17
Slide 18
Slide 18 text
I originally used Data because I vaguely assumed Data/Struct
was lighter than Class.
Reality was different at least object initialization. Did you know
that?
Summary
18
Slide 19
Slide 19 text
〜Fin〜
19
Slide 20
Slide 20 text
🤔
20
Slide 21
Slide 21 text
If "Class" is the fastest, why not re-implement these with it??
🤔🤔🤔
How to speed up Struct or Data.define
21
Slide 22
Slide 22 text
Re-impl Struct with "Class", and benchmark again:
(8 fields, YJIT off/on)
How to speed up Struct or Data.define
22
Slide 23
Slide 23 text
It’s really fast! Let’s submit this patch!!!
Slide 24
Slide 24 text
Let’s submit this patch!!!
24
Slide 25
Slide 25 text
Submit this patch…?
25
Slide 26
Slide 26 text
🫠
26
Slide 27
Slide 27 text
🚮
27
Slide 28
Slide 28 text
28
You can check the full benchmark & RubyStruct implementation!
https://github.com/riseshia/class-new-is-all-you-need
Class.new might be all you need
(if initialization perf matters)