代码之家  ›  专栏  ›  技术社区  ›  user2906085

优化以下代码

  •  0
  • user2906085  · 技术社区  · 12 年前

    我有两个活动记录 StudentDemographics 和 StudentWeeklyReport 两者都有 has_many 关系如下:

    class StudentDemographics < ActiveRecord::Base
      has_many :student_weekly_reports, :foreign_key => :student_id
    end
    

    我必须在最后一次第五周的研讨会上与最近一次的研讨会核对每个学生的分数。如果结果是 true ,学生应该活跃,否则就不活跃。我有以下代码。在这里,我重复每个日期的循环。 @distinct 是一个日期数组。

     for i in 0...@distinct.length
         active = 0
         inactive = 0
         sum = safe.length
         @students = StudentDemographics.where("date <= ?", @distinct[i]).select("student_id") - safe
         @students.each do |student|
            @stu = StudentWeeklyReport.where(:student_id => student.student_id).select("student_id,golden_eggs").last(5)
                if @stu.length > 4
                    if @stu[4].golden_eggs > @stu[0].golden_eggs
                      safe << student
                      active += 1
                    else
                      inactive += 1
                    end
                else
                    safe << student
                    active += 1
                end
          end
          @active[i] = active + sum
          @inactive[i] = inactive
    end
    

    性能不好。它需要超过3秒的时间。my-mysql-db有13600英寸 StudentWeeklyReports 表和2000英寸 学生人口统计 桌子有人能建议如何优化以下代码吗?

    2 回复  |  直到 12 年前
        1
  •  1
  •   Thaha kp    12 年前
         @students = StudentDemographics.includes(:student_weekly_reports) - safe
     for i in 0...@distinct.length
         active = inactive = 0
         @students.each do |student|
            next if student.date > @distinct[i]
            @stu = student.student_weekly_reports.select("golden_eggs").last(5)
                if @stu.length > 4 && (@stu[4].golden_eggs <= @stu[0].golden_eggs)
                    inactive += 1
                else
                    safe << student
                    active += 1
                end
          end
          @active[i] = active + safe.length
          @inactive[i] = inactive
    end
    
        2
  •  0
  •   Amit Thawait    12 年前
    @students = StudentDemographics.includes(:student_weekly_reports).where("date <= ?", @distinct.min).select("student_id")
    # The above line will fetch all the necessary records you require 
    
    for i in 0...@distinct.length
     active = inactive = 0
     @students = @student.select { |student_demographics| student_demographics.date <= @distinct[i] } - safe
     @students.each do |student|
       @stu = student.student_weekly_reports.select("golden_eggs").last(5)
       if @stu.length > 4 and (@stu[4].golden_eggs <= @stu[0].golden_eggs)
         inactive += 1
       else
         safe << student
         active += 1
       end
      end
      @active[i] = active + safe.length
      @inactive[i] = inactive
    end
    
    推荐文章