From fd0c772db7e5098c2b8e03559317a3592074dfe7 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Sat, 30 Aug 2025 10:51:03 +0200 Subject: Micro-optimize Object#class Since `BUILTIN_TYPE` and `RCLASS_SINGLETON_P` are both stored in `RBasic.flags`, we can combine these two checks in a single bitmask. This rely on `T_ICLASS` and `T_CLASS` not overlapping, and assume `klass` is always either of these types. Just combining the masks brings a small but consistent 1.08x speedup on the simple case benchmark. ``` compare-ruby: ruby 3.5.0dev (2025-08-30T01:45:42Z obj-class 01a57bd6cd) +YJIT +PRISM [arm64-darwin24] built-ruby: ruby 3.5.0dev (2025-08-30T09:56:24Z obj-class 2685f8dbb4) +YJIT +PRISM [arm64-darwin24] | |compare-ruby|built-ruby| |:----------|-----------:|---------:| |obj | 444.410| 478.895| | | -| 1.08x| |extended | 135.139| 140.206| | | -| 1.04x| |singleton | 165.155| 155.832| | | 1.06x| -| |immediate | 380.103| 432.090| | | -| 1.14x| ``` But with the RB_UNLIKELY compiler hint, it's much more significant, however the singleton and enxtended cases are slowed down. However we can assume the simple case is way more common than the other two. ``` compare-ruby: ruby 3.5.0dev (2025-08-30T01:45:42Z obj-class 01a57bd6cd) +YJIT +PRISM [arm64-darwin24] built-ruby: ruby 3.5.0dev (2025-08-30T09:51:01Z obj-class 12d01a1b02) +YJIT +PRISM [arm64-darwin24] | |compare-ruby|built-ruby| |:----------|-----------:|---------:| |obj | 444.951| 556.191| | | -| 1.25x| |extended | 136.836| 113.871| | | 1.20x| -| |singleton | 166.335| 167.747| | | -| 1.01x| |immediate | 379.642| 509.515| | | -| 1.34x| ``` --- object.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'object.c') diff --git a/object.c b/object.c index a7def50cd7..9a770e64f9 100644 --- a/object.c +++ b/object.c @@ -288,10 +288,23 @@ rb_class_real(VALUE cl) return cl; } +static inline VALUE +fake_class_p(VALUE klass) +{ + RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS) || RB_TYPE_P(klass, T_ICLASS)); + STATIC_ASSERT(t_iclass_overlap, !(T_CLASS & T_ICLASS)); + + return FL_TEST_RAW(klass, T_ICLASS | FL_SINGLETON); +} + VALUE rb_obj_class(VALUE obj) { - return rb_class_real(CLASS_OF(obj)); + VALUE cl = CLASS_OF(obj); + while (RB_UNLIKELY(cl && fake_class_p(cl))) { + cl = RCLASS_SUPER(cl); + } + return cl; } /* -- cgit v1.2.3