I had this problem come up a while back (in fact I think
it was my question that prompted the thread on fwp about
it . . .). At any rate, this was something I had lying
around from it that benchmarks three solutions. You can
decide for yourself if the first is cheating or if you really,
really care about speed. :)
Also, note that these are returning the length of the common
string not the string itself.
#!/usr/bin/perl
use Benchmark qw( cmpthese );
use Inline C => <<EOF;
int comlen(char *p, char *q) {
int i = 0;
while( *p && (*p++ == *q++) )
i++;
return i;
}
EOF
sub comlen_or {
length((($_[0]^$_[1])=~m/^(\0+)/)[0]);
}
sub comlen_tr {
my( $t );
return ($t=$_[0]^$_[1])=~ y/\0/\0/;
}
$a = "abcdefghijk";
$b = "abcdefg";
cmpthese( shift || 2_000_000,
{
inline_c => sub { comlen( $a, $b ) },
comlen_or => sub { comlen_or( $a, $b ) },
comlen_tr => sub { comlen_tr( $a, $b ) },
},
);
exit 0;
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|