Dear monks,
When I run the following code:
#!/usr/bin/perl use strict; use feature 'say'; sub foo { my @a = 'aaaaa' .. 'zzzzz'; say time; return [ @a ]; } say time; my $a = foo(); say time;
I get this for output:
1370302025 1370302028 1370302032
Whereas, when I run this code:
#!/usr/bin/perl use strict; use feature 'say'; sub foo { my @a = 'aaaaa' .. 'zzzzz'; say time; return \@a; } say time; my $a = foo(); say time;
I get this output:
1370302601 1370302604 1370302604
In other words, in the former case, two huge arrays are created, but in the latter case, only one huge array is created. My question is: Why doesn't perl optimize the former code to only produce one huge array? It must know that the reference count on @a goes to zero at the same time it's copied. Can't it optimize the former's return statement to work just like the latter's? Is it really as simple as it seems, or am I overlooking some complicating factor(s)?
In reply to Why doesn't perl optimize this? by nbtrap
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |