Skip to content

Instantly share code, notes, and snippets.

@wanabe
Created April 9, 2012 14:21
Show Gist options
  • Save wanabe/2343759 to your computer and use it in GitHub Desktop.
Save wanabe/2343759 to your computer and use it in GitHub Desktop.
patch for CRuby. make Array#collect faster.
Index: array.c
===================================================================
--- array.c (revision 35267)
+++ array.c (working copy)
@@ -2255,12 +2255,19 @@ static VALUE
rb_ary_collect(VALUE ary)
{
long i;
- VALUE collect;
+ VALUE collect, v;
RETURN_ENUMERATOR(ary, 0, 0);
collect = rb_ary_new2(RARRAY_LEN(ary));
+ ARY_SET_LEN(collect, RARRAY_LEN(ary));
+ rb_mem_clear(RARRAY_PTR(collect), RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
- rb_ary_push(collect, rb_yield(RARRAY_PTR(ary)[i]));
+ v = rb_yield(RARRAY_PTR(ary)[i]);
+ if (RARRAY_LEN(collect) > i) {
+ RARRAY_PTR(collect)[i] = v;
+ } else {
+ rb_ary_push(collect, v);
+ }
}
return collect;
}
@@ -2288,11 +2295,22 @@ static VALUE
rb_ary_collect_bang(VALUE ary)
{
long i;
+ VALUE v;
RETURN_ENUMERATOR(ary, 0, 0);
rb_ary_modify(ary);
- for (i = 0; i < RARRAY_LEN(ary); i++) {
- rb_ary_store(ary, i, rb_yield(RARRAY_PTR(ary)[i]));
+ if (RARRAY_LEN(ary) == 0) {
+ return ary;
+ }
+ i = 0;
+ for (;;) {
+ v = rb_yield(RARRAY_PTR(ary)[i]);
+ if (RARRAY_LEN(ary) - 1 > i) {
+ RARRAY_PTR(ary)[i++] = v;
+ } else {
+ rb_ary_store(ary, i, v);
+ break;
+ }
}
return ary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment