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

Dear monks,

Apologies if this question has an obvious answer... Which is faster (in execution time?)
if ($value =~ /^string$/)
or
if ($value eq 'string')
Moreover, which of the following two is faster ( I am aware that they are not equivalent, but in my case can use both):
if ($value =~ /^string$/)
or
if ($value =~ /string/)
Thanks in advance,

Athanasia

Update:
Thanks to all providing me with interesting insights of the problem and to their recommendations.

Replies are listed 'Best First'.
Re: Regular expression matching or eq, which is faster?
by GrandFather (Saint) on May 11, 2009 at 10:19 UTC

    'faster' and 'most efficient' are often the subject of questions to PerlMonks and almost always the answer is one of:

    • It depends
    • Benchmark it
    • It is fast enough
    • Why does it matter?

    In this case I suspect all four answers apply. It depends on the version of Perl you are using. With 5.10 (I understand) the special case you are dealing with can be almost as fast as eq.

    To find out, bench mark your actual use cases using Benchmark (but make sure you are testing what you think you are).

    But in any case, either version is likely to be fast enough. Most likely if you are having performance issues your problem is elsewhere which leads right to:

    Why does it matter?


    True laziness is hard work
Re: Regular expression matching or eq, which is faster?
by moritz (Cardinal) on May 11, 2009 at 10:28 UTC
    The first question should be "are they the same, and if yes, which one is the correct one?"
    $ $ perl -wE 'say "ouch" if "foo\n" =~ /^foo$/' ouch $ perl -wE 'say "ouch" if "foo\n" eq "foo"' $ # no output

    So they are not the same... which one do you want?

Re: Regular expression matching or eq, which is faster?
by citromatik (Curate) on May 11, 2009 at 10:21 UTC
    • If you are looking for equality between two strings, use eq
    • If you need to match against a regular expression, use a regular expression
    • If your regular expression needs to match from the beginning of the string, use the ^ anchor. If your regular expression matches until the end of the string, use the $ anchor

    citromatik

Re: Regular expression matching or eq, which is faster?
by ww (Archbishop) on May 11, 2009 at 10:26 UTC

    Available answers: "a" and/or "b" and/or "sometimes one, sometimes the other."

    You may find it useful to read Benchmarking Your Code which is among the nodes identified by Super Search.

    IMHO, this is probably one of the cases in which "try it" will best lead you on the path to wisdom.

Re: Regular expression matching or eq, which is faster?
by Utilitarian (Vicar) on May 11, 2009 at 10:25 UTC
    A quick benchmark indicates that if ($value =~ /string/) is tied with if ($value eq 'string')

    with if ($value =~ /^string$/) taking twice as long