From 20c5f60775b8691c3f41830da1534f7ec92edf40 Mon Sep 17 00:00:00 2001 From: glass Date: Fri, 25 Aug 2017 08:13:32 +0000 Subject: csv.rb: optimize CSV::Table#to_a and #to_csv * lib/csv.rb (CSV::Table#to_a, #to_csv): use Array#push instead of Array#concat for performance improvement. This performance improvement is proposed by zdennis . The patch is from Mau Magnaguagno . close #946 git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@59657 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- lib/csv.rb | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) (limited to 'lib') diff --git a/lib/csv.rb b/lib/csv.rb index 14025c1cd1..675e141356 100644 --- a/lib/csv.rb +++ b/lib/csv.rb @@ -879,13 +879,11 @@ class CSV # then all of the field rows will follow. # def to_a - @table.inject([headers]) do |array, row| - if row.header_row? - array - else - array + [row.fields] - end + array = [headers] + @table.each do |row| + array.push(row.fields) unless row.header_row? end + return array end # @@ -896,13 +894,11 @@ class CSV # pass :write_headers => false. # def to_csv(write_headers: true, **options) - @table.inject(write_headers ? [headers.to_csv(options)] : [ ]) do |rows, row| - if row.header_row? - rows - else - rows + [row.fields.to_csv(options)] - end - end.join('') + array = write_headers ? [headers.to_csv(options)] : [] + @table.each do |row| + array.push(row.fields.to_csv(options)) unless row.header_row? + end + return array.join('') end alias_method :to_s, :to_csv -- cgit v1.2.3