title: Laravel how to optimize an expensive calculation in memory?
body: <p>I wrote a function for an average calculation for a school class.
  The logic is:
  As input, I have a number of students, a number of subjects, a number of notes in each subject.
  Each student has an average in each subject.
  In each subject, the two-note student and the average of the two grades average the subject. In the absence of a note, the system sets a zero.
  There is a period to collect the notes and at the end of the collection, the system calculates the averages automatically.</p>
  
  <pre><code>//firt step, fill zero if note is missed
  foreach ($students  as $student){
    foreach ($subjects as $subject){
      $this-&gt;checkNotes($student,$subject);
     }
   }
  
  //step two, calcul avarage
  foreach ($students-&gt;chunk(100) as $chunk){
    foreach ($chunk as $student){
      foreach ($subjects as $subject){
         $this-&gt;subjectAverage($student, $subject)
        }
     }
  }
  </code></pre>
  
  <p>The function works with small volume of data. Example if I have 10 students, 5 subjects, 2 notes for each subject ... But when I have a big data request, eg: 50000 students, 30 subjects, 2 notes for each subject ... the application crashes the whole system. I tried to implement the function as chunk () on the candidate collection but I still have the same results. How to optimize such a calculation? thanks for the help</p>