Topic: another performance question

hello there,

i am having another performance issuse.

i have a function in a model that looks like this

def total_wet_time
        wet_time = 0
        self.status_changes.each do |change|
            if StatsList.is_wet(change.after)
                next_change = get_next_change(change.date_time)
                if ! next_change.nil?
                    diff =  next_change.date_time.to_i - change.date_time.to_i
                    wet_time += diff
                end
            end
        end       
        return wet_time                   
end

now to get total_wet_time, the whole list is pulled for the self.status_changes ( usually about 300 records each.

now in the same page, i use this value to compute a few different values that will also be displayed. And each time it has to go through this whole process again. This makes a huge drag on the page loading.

so, i was wondering, is there something i can put in here that if this value has already been computed, it will return that value instead of going through all this over and over again ?

thanks

Re: another performance question

You can cache the value in an instance variable like this:

def total_wet_time
  @total_wet_time ||= calculate_total_wet_time
end

def calculate_total_wet_time
  wet_time = 0
  #...
  return wet_time
end


Now it will only be run once (per request), the 2nd time it will use the value which is in the instance variable.

Railscasts - Free Ruby on Rails Screencasts

Re: another performance question

Way cool, there are a dozen different places that i can implement this.

Thanks much !