An Inline::C implementation runs about three times faster than the string interpolation version for integer comparison, and about 2.5 times faster for string comparisons.

use v5.16; use strict; use warnings; use Inline 'C'; sub arrays_same_pp { "@{$_[0]}" eq "@{$_[1]}"; } our @x = map { int(rand() * 1_000_000) } 1..10; our @y = @x; use Benchmark 'cmpthese'; cmpthese -1, { PP => '::arrays_same_pp(\@::x, \@::y)', XS => '::arrays_same_i(\@::x, \@::y)', }; __END__ __C__ int arrays_same_i (SV* x, SV* y) { AV* arrx = (AV*)SvRV(x); AV* arry = (AV*)SvRV(y); if (arrx == arry) { return 2; } int len = av_len(arrx); if (len != av_len(arry)) { return 0; } int i; for (i=0; i<=len; i++) { SV** elemx = av_fetch(arrx, i, 0); SV** elemy = av_fetch(arry, i, 0); int ix = SvIV(*elemx); int iy = SvIV(*elemy); if (ix != iy) { return 0; } } return 1; } int arrays_same_s (SV* x, SV* y) { AV* arrx = (AV*)SvRV(x); AV* arry = (AV*)SvRV(y); if (arrx == arry) { return 2; } int len = av_len(arrx); if (len != av_len(arry)) { return 0; } int i; for (i=0; i<=len; i++) { SV** elemx = av_fetch(arrx, i, 0); SV** elemy = av_fetch(arry, i, 0); STRLEN dummy; char* strx = SvPV(*elemx, dummy); char* stry = SvPV(*elemy, dummy); if (strcmp(strx, stry) != 0) { return 0; } } return 1; }

I might clean this up and release to CPAN if there's nothing similar already there.


In reply to Re^2: Speed of comparison of two one-dimensional arrays by tobyink
in thread Speed of comparison of two one-dimensional arrays by rsFalse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.