This project is archived and is in readonly mode.

#3549 ✓stale

ActiveRecord::Base#create has a performance loss

Reported by sserdyuk | December 8th, 2009 @ 02:23 AM

I was profiling my application and noticed that serialized attributes are encoded into yaml twice. The reason is that ActiveRecord::Base#create is calling #quoted_column_names without specifying quoted attributes that it already calculated, which causes the second call to #attributes_with_quotes, which encodes serialized attributes into yaml. I have noticed it because I have a large hash in that attribute, which takes 3+ seconds to #to_yaml.

This is in Rails 2.3.5. I haven't looked into the older versions.

My fix for it was to monkey patch AR:Base with:

  def create_without_timestamps
    if && connection.prefetch_primary_key?(self.class.table_name) = connection.next_sequence_value(self.class.sequence_name)

    quoted_attributes = attributes_with_quotes

    statement = if quoted_attributes.empty?
      "INSERT INTO #{self.class.quoted_table_name} " +
      #"(#{quoted_column_names.join(', ')}) " + # original
      "(#{quoted_column_names(quoted_attributes).join(', ')}) " + # providing an existing set of attributes to avoid performance penalty
      "VALUES(#{quoted_attributes.values.join(', ')})"
    end = connection.insert(statement, "#{} Create",
      self.class.primary_key,, self.class.sequence_name)

    @new_record = false

Comments and changes to this ticket

  • Rohit Arondekar

    Rohit Arondekar October 7th, 2010 @ 12:01 PM

    • State changed from “new” to “stale”
    • Importance changed from “” to “Low”

    Marking ticket as stale. If this is still an issue please leave a comment with suggested changes, creating a patch with tests, rebasing an existing patch or just confirming the issue on a latest release or master/branches.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

People watching this ticket