2006年12月29日(金) [過去の今日]
#2 perlでSingleton
デザインパターンにSingletonってのがあるらしい。ORMのインスタンスを使いまわす方法がわからなくて悩んでたのでちょうどいい。 IBMのサイトにあった記事 をそのままperlでやってみよう。
package Misao::Singleton; use strict; my $instance; sub __new { my $class = shift; my $self = {}; bless $self, $class; return $self; } sub new { $instance or $instance = __new(@_); return $instance; } 1;
ってな感じにクラスを作って、ベンチマークのスクリプトを書く。
#!/usr/bin/perl use strict; use Benchmark; use Misao::Singleton; timethese(10000000, { normal => q{ my $instance = Misao::Singleton->__new(); }, singleton => q{ my $instance = Misao::Singleton->new(); } });
でもって結果は、
$ perl singleton.pl Benchmark: timing 10000000 iterations of normal, singleton... normal: 30 wallclock secs (28.87 usr + 0.07 sys = 28.94 CPU) @ 345542.50/s (n=10000000) singleton: 13 wallclock secs (13.65 usr + 0.05 sys = 13.70 CPU) @ 729927.01/s (n=10000000)
ほお、倍速か。
できれば消費メモリ量もどれくらい変わるか見てみたいけど、やり方わからん。まあ必要無いか。
(@961)