i was hoping you might be able to explain the following to me - taken from a website - it shows 2 ways of doing the same thing and one way is supposed to be be 'better' than the other and i don't understand the difference.
i don't understand why the while/shift is more efficient on memory. Here is the website's explanation# get_all_Genes returns returns a list reference #each item in the list is a gene reference # Iterate through all of the genes on a clone foreach my $gene ( @{ $first_clone->get_all_Genes() } ) { print $gene->stable_id(), "\n"; } # More memory efficient way of doing the same thing my $genes = $first_clone->get_all_Genes(); while ( my $gene = shift @{$genes} ) { print $gene->stable_id(), "\n"; }
I thought that both the foreach loop and the while/shift loop will return a gene reference from the gene list and the data in the gene will be populated as needed in the get method for the gene object. So how is foreach better in memory usage than the while/shift as they are both just getting gene references off the list and not getting any data from the gene object thanks a lotSome of the data that makes up the objects returned from the Ensembl A +PI is lazy loaded. By using lazy loading, we are able to minimize the + number of database queries and only "fill in" the data in the object + that the program actually asked for. This makes the code faster and +its memory footprint smaller, but it also means that the more data th +at the program requests from an object the larger it becomes. The con +sequence of this is that looping over a large number of these objects + in some cases might grow the memory footprint of the program conside +rably. By using a while-shift loop rather than a foreach loop, the growth of +the memory footprint due to lazy loading of data is more likely to st +ay small. This is why the comment on the last loop above says that it + is a "more memory efficient way", and this is also why we use this c +onvention for most similar loop constructs in the remainder of this A +PI tutorial. NB: This strategy obviously won't work if the contents of the list bei +ng iterated over is needed at some later point after the end of the l +oop.
In reply to lazy loading and memory usage by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |