How remove leading zeros

The most efficient way to remove leading zeros from some number is add to that number 0:

      1 #! /usr/bin/perl -w
2
3 use strict;
4 use Benchmark;
5
6 my $test = '000000000000001';
8 timethese shift,
9 {
10 Add => sub { my $num = $test; $num += 0 },
11 Regex => sub { my $num = $test; $num =~ s/^0+// },
12 Sprintf => sub { my $num = $test; $num = sprintf '%d', $num },
13 };

Benchmark: timing 10000000 iterations of Add, Regex, Sprintf…
Add: 26 wallclock secs (17.68 usr + 0.06 sys = 17.74 CPU) @ 563697.86/s (n=10000000)
Regex: 48 wallclock secs (38.32 usr + 0.09 sys = 38.41 CPU) @ 260348.87/s (n=10000000)
Sprintf: 43 wallclock secs (34.78 usr + 0.10 sys = 34.88 CPU) @ 286697.25/s (n=10000000)

Published by

Michael Stepanov

Site owner and admin :)

Leave a Reply

Your email address will not be published. Required fields are marked *