Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveRecord::Base#create has a performance loss

#3549

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 self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
      self.id = connection.next_sequence_value(self.class.sequence_name)
    end

    quoted_attributes = attributes_with_quotes

    statement = if quoted_attributes.empty?
      connection.empty_insert_statement(self.class.table_name)
    else
      "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

    self.id = connection.insert(statement, "#{self.class.name} Create",
      self.class.primary_key, self.id, self.class.sequence_name)

    @new_record = false
    id
  end

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

State: stale
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Rohit Arondekar
    Rohit Arondekar
    • 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.

    October 7th, 2010 @ 12:01 PM