This project is archived and is in readonly mode.

#3549 ✓stale
sserdyuk

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 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

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="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages