-   Programming (
-   -   Perl: Optimising List Assignment (

mistersnorfles 08-20-2007 12:26 PM

Perl: Optimising List Assignment
If I am copying the values from a function that returns a list value to a list of scalars, and I don't need all of the function's returns, do I gain any performance increase by assigning the unused values to undef? For example let's say I was using the localtime function, and all I wanted was the day, month, and year:

I could do this:

my($sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst)
= localtime 1180630098;

but I am wondering if this would be more efficient (speed-wise and memory-wise):


my(undef, undef, undef, $day, $mon, $year, undef, undef, undef)
= localtime 1180630098;

since the memory doesn't have to be allocated for the new variables, and the extra copying doesn't have to be done.

Is this true?

Mr. Snorfles

mistersnorfles 08-20-2007 03:40 PM

I looked over my post, and realized that would create a nine variable array -- probably not helpful. Any ideas how I should go about getting only those three values?

Mr. snorfles

chrism01 08-20-2007 07:41 PM

Here ya go:

($DAY, $MONTH, $YEAR) = (localtime)[3,4,5];

mistersnorfles 08-20-2007 09:29 PM

Thanks... I didn't know you could do the indexing on lists like that.

--Mr. Snorfles

bigearsbilly 08-21-2007 05:09 AM

but, i don't think you'll gain much in speed or memory.
Remember, localtime is making a slow system call anyway - so whether it return 9 or 3 will be a drop in the bucket timewise.

chrism01 08-21-2007 09:41 PM

As BB said, it's the overall fn elapsed time, not the num of returned values.
However, this sounds like 'premature optimization'.
If you really ALREADY have performance issues, a better (overall) algorithm will give you much larger gains.
You won't get anything out of fooling around with this stuff above.
Perhaps you could tell show us your code & mention where it seems slow?

All times are GMT -5. The time now is 05:20 AM.