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

Once more I come to the fount of wisdom. I come with a new question regarding my optimization quest: I'm currently assigning values to six strings using the ternary operator, viz.:

$x = ($y ne $q) ? $a : $b

Is this the fastest way to assign these values, or would the longer (and uglier) if--else be faster?

Thanks!

Diz

janitored by ybiC: retitle from non-descriptive and search-hostile "Gentle Monks, &c."

Replies are listed 'Best First'.
Re: Optimize string value assignment
by liz (Monsignor) on Aug 28, 2003 at 15:04 UTC
    Answer the question yourself: Benchmark.

    And beware that premature optimization is the root of all evil ;-)

    Liz

Re: Optimize string value assignment
by Aristotle (Chancellor) on Aug 28, 2003 at 15:34 UTC
    It doesn't matter. (Unless you're doing this many million times per second in a tight loop.)

    Makeshifts last the longest.

Re: Optimize string value assignment
by Zaxo (Archbishop) on Aug 28, 2003 at 16:07 UTC

    Don't forget that ?: is also an lvalue. Next week you can spend many happy afternoons working out what a nest of things like $c eq $d ? $c ? $d : $c : $e : $f = $g ne $h ? $i : $j; means.

    The trinary operator is not the problem with understanding code like that. Great heaps of hard-coded ununified opaque logic are. Redesign is the answer.

    Update: Heh, got carried away, CombatSquirrel++ spotted too many terms on the left. Repaired, it might read (if that's the word for it), $c eq $d ? $c ? $d : $c : $e = $g ne $h ? $i : $j; It all helps prove the point that micro-optimizing logical operations is less important than making them fit the application and the humans who must understand it.

    After Compline,
    Zaxo

      It means problems caused by a syntax error ;-). What about two instead of three colons on the LHS?
      Cheers,
      CombatSquirrel.
      Entropy is the tendency of everything going to hell.
Re: Optimize string value assignment
by TomDLux (Vicar) on Aug 28, 2003 at 15:57 UTC

    Is if-then-else generally a fast operation or is it one of the bugbears that drags down script performnce?

    Assuming if-then-else and the ternary operator are not identical under the covers, would you expect one to be 10% faster than the other? 100% faster? 1,000% faster?

    You have six instances of the ternary operator. If you could re-code these using the magic poof operator, they would take no time at all. How much change would that make in the performance of your script?

    --
    TTTATCGGTCGTTATATAGATGTTTGCA