2

I have a big rails application in which I have tons of models. I have reorganized the content of the models to follow a common pattern (positions of the fields, constants, relations, validations, hooks and so on on all files). After finishing of doing this process, I have realized that the tests are slower (a controller test which takes 40 seconds, now it uses more than 1 minute).

I have spent a lot of time trying to find the reason and finally I have found the problem. When I declare the validations after the relations, it takes more time to pass the tests (and the performarcen of the application is worse):

class Model
  include Mongoid::Document

  ## Fields
  ...

  ## Relations
  ...

  ## Validations
  ...
end

On the opposite, if I declare the relations after the validations, the performance is the same as previous:

class Model
  include Mongoid::Document

  ## Fields
  ...

  ## Validations
  ...

  ## Relations
  ...
end

I can't find a reason of this behaviour. Maybe it is because I am using mongoid 3 and this type of things are not happening with the next versions. However, for me it is more reasonable to have the relations before the validations because some of the validations reference to the relations.

UPDATE:

I can't put the original code but I have created a little rails application to show this behaviour. On my computer, it takes 3.02-3.03 seconds when validations are inmediately after the fields and 3.26-3.30 seconds when validations are after the relations. You can see the repository on the following link: weird_mongoid_behaviour.

I am not following the best practices for this application because it is an example. Sorry in advance.

  • 1
    The actual order should not really matter that much. You are basically just setting up callbacks in the class level which are run when `.valid?` is called in the model. The validations and relations etc really only read once when the class is evaluated - they do their metaprogramming magic and add methods to the class. – max Apr 30 '16 at 11:39
  • I know that... or I think that I know that. If I don't find another solution, I will have to change the order between validations and relations in order to have a better performance. However I would like to know the reason. Thanks for your answer but what I am experiencing myself it is the opposite. – jesusgonzalezrivera Apr 30 '16 at 11:41
  • Can you produce a runnable benchmark that exhibits this behaviour? – Frederick Cheung Apr 30 '16 at 15:19
  • I have added a repository to the behaviour (on the UPDATE tag). – jesusgonzalezrivera May 08 '16 at 11:45

0 Answers0