I create a CSV file in Ror 3.1 by getting an external datatable(70 sec for select) then looping through that datatable and writing eachline of a CSV file. My data source usually has around 500,000 rows in it.This process takes 10 minutes to download from the browser. I use next code to generate csv
<%=
response.content_type = 'application/octet-stream'
CSV.generate(:col_sep => ?; ) do |csv|
csv << ['date', 'open', 'high', 'low', 'close']
@sql_testa.each do |row|
csv << row
end
end
%>
dev.log
500 000 rows: Rendered forex/index.csv.erb (965590.2ms) Completed 200 OK in 965621ms (Views: 965598.2ms | ActiveRecord: 3.0ms) CSV bencmark 963245.2ms
50 000 rows: Rendered forex/index.csv.erb (4986.3ms) Completed 200 OK in 5022ms (Views: 4994.3ms | ActiveRecord: 5.0ms) CSV benchmark 4413.3ms
How to optimize it? Should I use objective C to extend ruby? (and how?)
I delete CSV.generate and use just this code in index.csv.erb
$sql_testa.map{ |i| %Q('#{i}') }.join(",").delete("'[").gsub("],", "\n").delete('""').gsub(",", ";").gsub(/]\Z/,'')
Surprisingly that csv file also generated without CSV.generate and it takes 5 seconds. So, i solved it.