Skip to content

Instantly share code, notes, and snippets.

@karupanerura
Forked from kfly8/bench_arrayref.pl
Created October 16, 2018 06:05
Show Gist options
  • Save karupanerura/85eb36ad10e302d71b2e0414c82e1c50 to your computer and use it in GitHub Desktop.
Save karupanerura/85eb36ad10e302d71b2e0414c82e1c50 to your computer and use it in GitHub Desktop.
Benchmark JSON::Encode
use strict;
use warnings;
use JSON::XS qw(encode_json);
use Benchmark qw(cmpthese);
my $obj = [ map {
+{
name => 'foo',
age => 123,
fg => !!0,
};
} 0 .. 100];
{
my $src;
sub my_encode_ver2 {
my $obj = shift;
$src = '[';
{
for (@{$obj}) {
$src .= '{"name":"' . $_->{'name'} . '","age":' . ($_->{age} + 0) . ',"fg":' . ($_->{fg}? 'true':'false') . '},';
}
$src = substr($src, 0, -1);
}
$src .= ']';
return $src;
}
};
sub my_encode {
my $obj = shift;
return '['
. do {
my $src;
for (@{$obj}) {
$src .= '{"name":"' . $_->{'name'} . '","age":' . ($_->{age} + 0) . ',"fg":' . ($_->{fg}? 'true':'false') . '},';
}
substr($src, 0, -1);
}
. ']';
}
cmpthese -1, {
"my_encode" => sub { my_encode($obj) },
"my_encode_ver2" => sub { my_encode_ver2($obj) },
"JSON::XS" => sub { encode_json($obj) }
};
# Rate my_encode my_encode_ver2 JSON::XS
# my_encode 49123/s -- -5% -29%
# my_encode_ver2 51661/s 5% -- -25%
# JSON::XS 69200/s 41% 34% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment