title: How to generate .csv in Ror with 500 000 rows faster
body: <p>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</p>
  
  <pre><code>&lt;%=
  response.content_type = 'application/octet-stream'
  
  CSV.generate(:col_sep =&gt; ?; ) do |csv|
  csv &lt;&lt; ['date', 'open', 'high', 'low', 'close']
  @sql_testa.each do |row|
    csv &lt;&lt; row
  end
  end
  %&gt;
  </code></pre>
  
  <p>dev.log</p>
  
  <p>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</p>
  
  <p>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</p>
  
  <p>How to optimize it?
  Should I use objective C to extend ruby? (and how?)</p>
  
  <p>I delete CSV.generate and use just this code in index.csv.erb</p>
  
  <pre><code>$sql_testa.map{ |i|  %Q('#{i}') }.join(",").delete("'[").gsub("],", "\n").delete('""').gsub(",", ";").gsub(/]\Z/,'')
  </code></pre>
  
  <p>Surprisingly that csv file also generated without CSV.generate and it takes 5 seconds. So, i solved it.</p>