From 6ae2996e291750bab4ff59a06ba11c8d6bbe5aaa Mon Sep 17 00:00:00 2001 From: Kouhei Yanagita Date: Thu, 5 Oct 2023 00:19:55 +0900 Subject: Optimize `Range#count` by using `range_size` if possible --- range.c | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) (limited to 'range.c') diff --git a/range.c b/range.c index d0e0c4c1af..e57ffef7e5 100644 --- a/range.c +++ b/range.c @@ -607,6 +607,10 @@ double_as_int64(double d) static int is_integer_p(VALUE v) { + if (rb_integer_type_p(v)) { + return true; + } + ID id_integer_p; VALUE is_int; CONST_ID(id_integer_p, "integer?"); @@ -2166,17 +2170,22 @@ range_count(int argc, VALUE *argv, VALUE range) * Infinity. Just let it loop. */ return rb_call_super(argc, argv); } - else if (NIL_P(RANGE_END(range))) { - /* We are confident that the answer is Infinity. */ - return DBL2NUM(HUGE_VAL); - } - else if (NIL_P(RANGE_BEG(range))) { + + VALUE beg = RANGE_BEG(range), end = RANGE_END(range); + + if (NIL_P(beg) || NIL_P(end)) { /* We are confident that the answer is Infinity. */ return DBL2NUM(HUGE_VAL); } - else { - return rb_call_super(argc, argv); + + if (is_integer_p(beg)) { + VALUE size = range_size(range); + if (!NIL_P(size)) { + return size; + } } + + return rb_call_super(argc, argv); } static bool -- cgit v1.2.3