Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Optimize the rary_splice().

* before
               user     system      total        real
len == rlen  0.860000   0.000000   0.860000 (  0.852845)
len != rlen 21.180000   0.010000  21.190000 ( 21.186979)

* after
                user     system      total        real
len == rlen  0.050000   0.000000   0.050000 (  0.056620)
len != rlen  0.150000   0.000000   0.150000 (  0.145373)

{{{
require 'benchmark'

Benchmark.bm(10) do |x|
  ary =  Array.new(1000)
  tmp =  ["a"] * 1100
  x.report "len ==  rlen" do
    10000.times do
      ary[100, tmp.size] =  tmp
    end
  end

  x.report "len !=  rlen" do
    10000.times do
      ary[100, tmp.size - 1] =  tmp
    end
  end
end
}}}
  • Loading branch information...
commit 8b4d3bd0129c385668b1933ec646a14591661489 1 parent c890444
@Watson1978 Watson1978 authored
Showing with 28 additions and 6 deletions.
  1. +28 −6 array.c
View
34 array.c
@@ -942,14 +942,36 @@ rary_splice(VALUE ary, long beg, long len, VALUE rpl)
}
}
else if (len == rlen) {
- for (long i = 0; i < len; i++) {
- rary_elt_set(ary, beg + i, rb_ary_elt(rpl, i));
- }
+ if (rlen > 0 && IS_RARY(rpl)) {
+ GC_MEMMOVE(&RARY(ary)->elements[RARY(ary)->beg + beg],
+ &RARY(rpl)->elements[RARY(rpl)->beg],
+ sizeof(VALUE) * len);
+ }
+ else {
+ for (long i = 0; i < len; i++) {
+ rary_elt_set(ary, beg + i, rb_ary_elt(rpl, i));
+ }
+ }
}
else {
- rary_erase(ary, beg, len);
- for (long i = 0; i < rlen; i++) {
- rary_insert(ary, beg + i, rb_ary_elt(rpl, i));
+ if (rlen > 0 && IS_RARY(rpl)) {
+ long newlen = RARY(ary)->len + rlen - len;
+
+ rary_reserve(ary, newlen);
+ GC_MEMMOVE(&RARY(ary)->elements[RARY(ary)->beg + beg + rlen],
+ &RARY(ary)->elements[RARY(ary)->beg + beg + len],
+ sizeof(VALUE) * (RARY(ary)->len - (beg + len)));
+
+ GC_MEMMOVE(&RARY(ary)->elements[RARY(ary)->beg + beg],
+ rary_ptr(rpl),
+ sizeof(VALUE) * rlen);
+ RARY(ary)->len = newlen;
+ }
+ else {
+ rary_erase(ary, beg, len);
+ for (long i = 0; i < rlen; i++) {
+ rary_insert(ary, beg + i, rb_ary_elt(rpl, i));
+ }
}
}
}
Please sign in to comment.
Something went wrong with that request. Please try again.