Note that there are some explanatory texts on larger screens.

plurals
  1. POperformance difference between while (each) and foreach in Perl
    primarykey
    data
    text
    <p>The hash that I tested contains around 70000 colleges and each college contains around 20 students. I tried it 5 times and following are the results. There is considerable difference in foreach performance and while (each) performance. Why is that so?</p> <p>Code with while loop:</p> <pre><code>while ( my ($college_code, $college_info_hr) = each (%{$college_data_hr}) ) { while ( my ($student_num, $student_info_hr) = each (%{$college_info_hr-&gt;{'students'}}) ) { if($student_num &lt; 104000) { ## Delete the info of students before 2004. delete $college_info_hr-&gt;{'students'}{$student_num}; } } } </code></pre> <p>Code with foreach loop:</p> <pre><code>foreach my $college_code (keys %{$college_data_hr}) { foreach my $student_num (keys %{$college_data_hr-&gt;{$college_code}{'students'}}) { if($student_num &lt; 104000) { ## Delete the info of students before 2004. delete $college_data_hr-&gt;{$college_code}{'students'}{$student_num}; } } } </code></pre> <p><strong>When the the number of colleges are 70,000 then the execution times are:</strong></p> <p>For the code with while loop (Interval time is in seconds):</p> <p>Interval time: 2.186621</p> <p>Interval time: 2.058644</p> <p>Interval time: 2.055645</p> <p>Interval time: 2.101637</p> <p>Interval time: 2.124632</p> <p>For the code with foreach loop: (Interval time is in seconds)</p> <p>Interval time: 1.341768</p> <p>Interval time: 1.436751</p> <p>Interval time: 1.346529</p> <p>Interval time: 1.302775</p> <p>Interval time: 1.356765</p> <p><strong>When the the number of colleges are 248,000 then the execution times are:</strong></p> <p>(execution times for while loop)</p> <p>Interval time: 9.084427</p> <p>Interval time: 8.438684</p> <p>Interval time: 9.329338</p> <p>Interval time: 9.169687</p> <p>(execution times for foreach loop)</p> <p>Interval time: 5.502048</p> <p>Interval time: 6.386692</p> <p>Interval time: 5.596032</p> <p>Interval time: 5.620144</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload