[前][次][番号順一覧][スレッド一覧]

ruby-changes:29987

From: glass <ko1@a...>
Date: Thu, 18 Jul 2013 17:48:25 +0900 (JST)
Subject: [ruby-changes:29987] glass:r42039 (trunk): * hash.c (rb_hash_flatten): performance improvement by not using

glass	2013-07-18 17:48:12 +0900 (Thu, 18 Jul 2013)

  New Revision: 42039

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=42039

  Log:
    * hash.c (rb_hash_flatten): performance improvement by not using
      rb_hash_to_a() to avoid array creation with rb_assoc_new().

  Modified files:
    trunk/ChangeLog
    trunk/hash.c

Index: ChangeLog
===================================================================
--- ChangeLog	(revision 42038)
+++ ChangeLog	(revision 42039)
@@ -1,3 +1,8 @@ https://github.com/ruby/ruby/blob/trunk/ChangeLog#L1
+Thu Jul 18 17:35:41 2013  Masaki Matsushita  <glass.saga@g...>
+
+	* hash.c (rb_hash_flatten): performance improvement by not using
+	  rb_hash_to_a() to avoid array creation with rb_assoc_new().
+
 Thu Jul 18 16:16:17 2013  Koichi Sasada  <ko1@a...>
 
 	* array.c: add logging feature for RGenGC's write barrier unprotect
Index: hash.c
===================================================================
--- hash.c	(revision 42038)
+++ hash.c	(revision 42039)
@@ -2187,6 +2187,18 @@ rb_hash_rassoc(VALUE hash, VALUE obj) https://github.com/ruby/ruby/blob/trunk/hash.c#L2187
     return args[1];
 }
 
+static int
+flatten_i(VALUE key, VALUE val, VALUE ary)
+{
+    VALUE pair[2];
+
+    pair[0] = key;
+    pair[1] = val;
+    rb_ary_cat(ary, pair, 2);
+
+    return ST_CONTINUE;
+}
+
 /*
  *  call-seq:
  *     hash.flatten -> an_array
@@ -2206,15 +2218,17 @@ rb_hash_rassoc(VALUE hash, VALUE obj) https://github.com/ruby/ruby/blob/trunk/hash.c#L2218
 static VALUE
 rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
 {
-    VALUE ary, tmp;
+    VALUE ary;
 
-    ary = rb_hash_to_a(hash);
-    if (argc == 0) {
-	argc = 1;
-	tmp = INT2FIX(1);
-	argv = &tmp;
+    ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
+    rb_hash_foreach(hash, flatten_i, ary);
+    if (argc) {
+	int level = FIX2INT(*argv) - 1;
+	if (level > 0) {
+	    *argv = INT2FIX(level);
+	    rb_funcall2(ary, rb_intern("flatten!"), argc, argv);
+	}
     }
-    rb_funcall2(ary, rb_intern("flatten!"), argc, argv);
     return ary;
 }
 

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]