EDIT --> Probably I should have print the return of model.filtered(function) before asking because I discovered that if you don't make a search() before filtered you just get the model object in return, not a recordset. So basically you have to search/browse first, no matter what.
I still wonder if it's better to get subrecords with a second search or filtered function.
I think we should absolutely avoid to use search() or filtered() in loops, but I see that search() seems to be more efficient for a little number of iterations, while filtered seems to be slightly better for a large number.. might that be a reason to prefer filtered over search?
___________________________________________________________________________________________________
Hello everyone, I'm testing performance for my project and I'm trying to figure out cases when i should use search() instead of filtered().
I ask because of 2 reasons:
1) I did some tests and I can see that generally self.env['model.name'].filtered() is much faster than self.env['model.name'].search([])
For example,
variable = self.env['model.name'].search([('name', '=', 'value')])
is about 800 microseconds for me, EVEN IF i already istantiated model or recordset with another search and perform search() on the model or recordset (in the latter case is like 600 microseconds but still worse than filtered)
When
variable = self.env['model.name'].filtered(lambda r: r.name == name)
is about 250 microseconds.
And if I try to iterate n times the instructions, the results are basically the same.
2) BUT i also see that in Odoo source code, models recordsets are firstly fetched by using search() or browse() , and only then the results are filtered.
Now, from what I understand, one problem of filtered() might be that if I need to fetch the full recordset of a model to be able loop through it, I probably need to use search (or maybe browse) because I don't think there is a way to get the full recordset out the filtered method.
But in other situations, where I just need to fetch a subrecordset or even a single record, why not directly use filtered if it's faster instead of make a search() and then filter it later? Can some one explain? I find very poor explanations about it. Thanks!
Thanks Cybrosys, so basically with search() you're fetching from database while filtered() doesn't make a query. Interesting.
By the way, your tutorials are very helpful!