This seems a bit faster:
#! /usr/bin/perl use warnings; use strict; my $start = tell DATA; sub orig { seek DATA, $start, 0; my $count = 0; while (<DATA>) { while (/(M+)/g) { $count++; } } return $count } sub ch { my $count = 0; seek DATA, $start, 0; while (<DATA>) { tr/M/M/s; # tr/MIO/MIO/s seems a bit slower for longer inp +uts. $count += tr/M//; } return $count } use Test::More; is(ch(), orig(), 'ch4'); done_testing(); use Benchmark qw{ cmpthese }; cmpthese(-3, { orig => \&orig, ch => \&ch, }); __DATA__ IIIIIIIIIIIMMMMMMMMMMMMOOOOOOOOOOOOMMMMMMMMMIIIIIIIIIMM IIIIIIMMMMOOOOOMMMMIIIIIIIIIIIIIMMIIII MIM IMI M

On my machine:

ok 1 - ch4 1..1 Rate orig ch orig 59645/s -- -34% ch 89860/s 51% --

I tested various other approaches ($count += () = /M+/g, split), but your original's speed was always the same or better.

Update: It seems to scale better with longer inputs, for 15K string, it shows 280%.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

In reply to Re: Faster way to do this? by choroba
in thread Faster way to do this? by Anonymous Monk

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.