summaryrefslogtreecommitdiff
path: root/object.c
diff options
context:
space:
mode:
authorJean Boussier <jean.boussier@gmail.com>2025-08-30 10:51:03 +0200
committerJean Boussier <jean.boussier@gmail.com>2025-08-30 14:14:10 +0200
commitfd0c772db7e5098c2b8e03559317a3592074dfe7 (patch)
treeb0d9d3f99a4df3ffe1493d9ee4f0a3c2568e3cd6 /object.c
parent01a57bd6cde82ad58f938d075f569d57048d8a60 (diff)
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| ```
Diffstat (limited to 'object.c')
-rw-r--r--object.c15
1 files changed, 14 insertions, 1 deletions
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;
}
/*