Reputation: 4829
UPDATE. Check these benchmarks to test it for yourself.
Should I store the collection of objects in a variable of some service like this:
ConfigService{
private def countries = Country.findAllBySomeCondition()
public def countries(){
return countries
}
}
or use:
ConfigService{
public def countries(){
return Country.findAllBySomeCondition()
}
}
If the collection will be used often only for read.
Upvotes: 2
Views: 282
Reputation: 3243
@GrailsGuy's answer is spot on and I'm gave him a +1. To provide you with some other options you could:
1) If your list of Countries doesn't change you could put them in an enum and avoid the DB all together.
2) If you give the user the ability to add/remove/edit Countries then you could cache the list like you are in example 1 but then when the user add/remove/edits a country you can force reload the list.
ConfigService{
private def countries
public def countries(){
if(countries == null) {
countries = Country.findAllBySomeCondition()
}
return countries
}
}
CountryService {
def configService
def addCountry() {
//Do add country stuff
configService.countries = null
}
}
This way you can cache the countries until they get updated. Like @GrailsGuy said though Hibernate will do this to some extent for you.
Upvotes: 1
Reputation: 34011
Depends. In your first example, the value is cached, which may be a little more efficient, but if at some point more Countries are added, they may not show up on your service call. However, if you call .countries()
often with your second example, you may incur some performance hits.
The best option would probably be to get some benchmarks as to how long the queries take, and decide whether it's best to try to cache the value yourself, or to ensure that it's always up-to-date. My suggestion would be to stick with the second example, as Hibernate handles some caching for you already, and chances are the list is not big enough to significantly hinder your app.
Upvotes: 2