use strict; use warnings; use feature 'say'; use Benchmark 'cmpthese'; use constant L => 1e5; my $str = '1' x L; substr $str, rand L, 1 , '0' for 1 .. L; use Inline C => << 'END_OF_C'; int test_c_3( SV* str ) { int i, tmp, acc, max; STRLEN len; char* buf = SvPVbyte( str, len ); len --; acc = 0; max = -2; for( i = 0; i < len; i ++ ) { acc += ( buf[ i ] == '1' ); // *** tmp = i - 2 * acc; if ( tmp > max ) max = tmp; } return max + acc + ( buf[ len ] == '1' ) + 1; } int test_c_4( SV* str ) { int i, tmp, acc, max; STRLEN len; char* buf = SvPVbyte( str, len ); len --; acc = 0; max = -2; for( i = 0; i < len; i ++ ) { if ( buf[ i ] == '1' ) acc ++; // *** tmp = i - 2 * acc; if ( tmp > max ) max = tmp; } return max + acc + ( buf[ len ] == '1' ) + 1; } END_OF_C say $^V; say 'String length: ', L; cmpthese -2, { c3 => sub { test_c_3( $str )}, c4 => sub { test_c_4( $str )}, }; __END__ v5.32.1 String length: 100000 Rate c4 c3 c4 8800/s -- -0% c3 8817/s 0% -- v5.42.0 String length: 100000 Rate c4 c3 c4 2511/s -- -71% c3 8755/s 249% --