Most efficient method of finding a model by ID with Model.find
I noticed that I can do a Model.find
in a number of ways (assuming @user is an instance of the User model):
User.find(2)
=> #<User id: 2, name: "Mike Swift", email: "valid@email.com", ... etc ...
OR
User.find(@user)
=> #<User id: 2, name: "Mike Swift", email: "valid@email.com", ... etc ...
OR
User.find(@user[:id])
=> #<User id: 2, name: "Mike Swift", email: "valid@email.com", ... etc ...
OR
User.f开发者_开发技巧ind(@user.id)
=> #<User id: 2, name: "Mike Swift", email: "valid@email.com", ... etc ...
Is there any real difference between the later three of these methods? (I already know User.find(n)
would be the fastest) I would imagine they all work in about the same time, but perhaps I'm wrong.
In terms of sql they all do the same thing.
User.find(2)
This will be the fastest because there is no conversion needed.
Then User.find(@user.id)
and User.find(@user[:id])
.
And finally User.find(@user
because rails needs convert the user to an ID.
User.find(2) should be faster as Rails doesn't have to do any work to figure out the id. The others require some level of message passing to get the id.
I doubt the difference is very significant though.
You could try all of them and look at your log to see how long it takes to get your response.
精彩评论