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