Hi Mahatmas,

the target is to get a string into an array.

split does it perfectly but is slow.

unpack is extremly fast but produces 97, 98, 99 instead of a,b,c

so you have to chr() it to get 'a' out of 97 - again slow

What would you suggest?

A sample code:

use strict;
use warnings;

        # Fill a buffer with bytes
my $begin = time();
my $buffer = '';
for( 0 .. 10_000 ) { $buffer .= "abcdef\x00ghik"; }
        #
        # Split is slow
        #
print "split 20 times\n";
for( 0 .. 20 ) {
        print "loop $_\n";
        my @a = split( //, $buffer );
}
printf( "split consumed %d second(s)\n", time() - $begin );
$begin = time();
        #
        # pack is extremly fast
        #
print "pack alone\n";
for( 0 .. 20 ) {
        print "loop $_\n";
        my @a = unpack( "C*", $buffer );
}
printf( "pack consumed %d seconds\n", time() - $begin );
$begin = time();
        #
        # pack is extremly fast but needs chr() to get characters - slow!
        #
print "pack and chr in map\n";
for( 0 .. 20 ) {
        print "loop $_\n";
        my @a = unpack( "C*", $buffer );
        map{ $_ = chr( $_ ) } @a;
}
printf( "pack and chr in map consumed %d seconds\n", time() - $begin );
exit;

In reply to Convert string to array - performance challenge by rtillian

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.