Polymorphic Assocations Inefficient?

The last project I was working on there was a discussion of removing all polymorphic associations from the application because they are inefficient. I was wondering if anyone knew when they are inefficient and at what point would you need to worry about this? - Thanks

Yikes.

This sounds like dangerous hand-waving to me. Did someone run benchmarks of both approaches and provide data?

If not, Iā€™d be very worried about this kind of ā€œoptimizationā€.

Note: Iā€™m not saying that polymorphic associations arenā€™t less efficient than non-polymorphic versions. Itā€™s just that guessing at what you need to optimize tends to be extremely unreliable.

3 Likes

I am not sure if any benchmarks were ran. Although running benchmarks was a common practice for any optimization change. The argument was ā€œRails polymorphism prevents database integrity and performance since it never uses an indexā€.

Maintaining database integrity and performance is currently over my head. With polymorphic associations being widely used in rails, I was surprised this was a concern. Seeing your response ā€œYikesā€ to this question reassures me that this should not be much of a concern right now in my career.

Iā€™m not absolutely sure, but I think that comment your teammates made about missing indexes is not correct. When I do polymorphic associations, I build an index on the id and the type columns, which means you have the indices Postgres needs to search the table.

I suppose there could be an integrity problem in the sense that you might specify a type that doesnā€™t correspond to a class if you edited a record, but the solution there would be to avoid editing the type column and let ActiveRecord do that work.

2 Likes