John Lam 1997 — 2026

RubyCLR can make ActiveRecord much, much faster

I spent some time writing some ActiveRecord code yesterday that used the Person.Contact table from the AdventureWorks sample database. This is a rather large table (~20,000 rows), so I decided to see how quickly ActiveRecord could load that table.

I was disappointed – it took nearly 11s on my MacBookPro to read 20,000 records from SQL Server. If I read the same number of records into a DataSet, it takes about 0.5s.

I was wondering if RubyCLR could improve on the performance of the SQL Server database adapter which relies on ADO to do the data access. After all, I should be faster at marshaling data than the win32ole library.

I wrote this bit of test code just now. It runs 2.5X faster than the ActiveRecord code. It’s not exactly a fair comparison since I’m not creating ActiveRecord objects. I’ll see what I can do later to rewrite the SQL Server adapter for ActiveRecord to use RubyCLR + ADO.NET.

auto_dispose(SqlConnection.new(CS)) do |conn|
conn.open
command = SqlCommand.new('select * from Person.Contact', conn)
reader = command.execute_reader
column_names = []
0.upto(reader.field_count - 1) do |index|
column_names << reader.get_name(index)
end
records = []
while reader.read
attributes = {}
0.upto(reader.field_count - 1) do |index|
attributes[column_names[index]] = reader.get_value(index)
end
records << attributes
end
puts records.length
end
3 archived reader comments

John Lam (2006/05/12)

It’s now faster, now just a 3X slowdown over DataSets. The reality is that for most client-side applications, this perf difference just doesn’t matter. After all, we’re retrieving 20,000 records (and from a local DB - network latency + server load would decrease the perf advantage of DataSets).

Amr (2006/05/14)

is find_by_sql as fast as this technique? Personally I would always want to get to a point (by optimizing the search condition beforehand )where I don’t have to get 20,000 records in the client before I can process the retrieved dataset. I would hate to work with million row tables if the main option was to load the whole dataset on the client side first.

John Lam (2006/05/14)

The rate-limiting step in all of this is loading the data into the array of hashtables. So it will affect things regardless of whether you use find_by_sql or the dynamic finders. I’m just using find_all here to retrieve a large set of data that I can do some perf tuning on. I’m by no way advocating reading 20,000 row data sets to do client side processing - I just look at this as an interesting performance test to see whether I can improve the performance of ActiveRecord when talking to SQL Server.