Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Which is better to use (for perormance, optimization, etc.)

my $var;
or
my $var = '';
or
my $var = undef;

or is there an even better way to declare a null variable?

Replies are listed 'Best First'.
Re: Basic optimization questions
by ikegami (Patriarch) on Sep 24, 2010 at 19:36 UTC

    The second does something different than the other two, so it won't even be considered here.

    The third is a proper superset of the first, so it will obviously take some extra time, but I've spent more time typing this then you will ever spend assigning undef to variables.

    You're going about optimising completely backwards. Spend time picking the right algorithm over worrying about micro optimisations. Don't spend time fixing problems that don't exist.

      This is like the traveling salesman worrying about whether to lock the doors himself or to let the electronics do it for him when he hits 20km/h.

Re: Basic optimization questions
by TomDLux (Vicar) on Sep 24, 2010 at 20:23 UTC

    The first option is the correct one.

    Assigning an empty string or zero is useful if you know you want to print the variable out, and you're not sure it will be assigned to. On the other hand if the assignment might assign undef, then you have to avoid warnings about undef at the print site, rather than at the declaration:

    print "Possibly undef var is " . $var || 'undef' . ".\n";

    Assigning undef is a waste of typing.

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

      The first option is the correct one. Assigning undef is a waste of typing.

      Not necessarily. Assigning undef has semantic meaning to some people. To them, "my $var = undef;" means "I am intentionally initialising it to undef, a value I might use.", and "my $var;" means "I am declaring a variable, but I still need to assign a value to it before using it."

      I just use "my $var;" unconditionally.

      The first option is the correct one.
      That implies the other options are wrong. The rest of your post doesn't convince me the other options are wrong.
Re: Basic optimization questions
by DrHyde (Prior) on Sep 27, 2010 at 09:57 UTC