प्रदर्शन इस मामले में महत्वपूर्ण नहीं है "डेवेल :: NYTProf"। लेकिन आपके सवाल का जवाब देने के लिए: अगर हैश में मूल्य मौजूद नहीं है
, "मौजूद है" बहुत तेजी से
if(exists $ids{$name}){
$id = $ids{$name};
}
है लेकिन अगर यह करने वाला दूसरा देखने किया जाता है मौजूद है। केवल एक ही स्वरूप को प्रभावी बनाने से मौजूद है, तो मूल्य की संभावना है हो जाएगा तेजी से
$id = $ids{$name};
if($id){
#....
}
एक पर्ल मेलिंग सूची से इस छोटे से बेंचमार्क देखते हैं।
#!/usr/bin/perl -w
use strict;
use Benchmark qw(timethese);
use vars qw(%hash);
@hash{ 'A' .. 'Z', 'a' .. 'z' } = (1) x 52;
my $key = 'xx';
timethese 10000000, {
'defined' => sub {
if (defined $hash{$key}) { my $x = $hash{$key}; return $x; };
return 0;
},
'defined_smart' => sub {
my $x = $hash{$key};
if (defined $x) {
return $x;
};
return 0;
},
'exists' => sub {
if (exists $hash{$key}) { my $x = $hash{$key}; return $x; };
return 0;
},
'as is' => sub {
if ($hash{$key}) { my $x = $hash{$key}; return $x; };
return 0;
},
'as is_smart' => sub {
my $x = $hash{$key};
if ($x) { return $x; };
return 0;
},
};
एक कुंजी ('xx') का उपयोग करके मौजूद नहीं है जो दिखाता है कि 'मौजूद' विजेता है।
Benchmark: timing 10000000 iterations of as is, as is_smart, defined, defined_smart, exists...
as is: 1 wallclock secs (1.52 usr + 0.00 sys = 1.52 CPU) @ 6578947.37/s (n=10000000)
as is_smart: 3 wallclock secs (2.67 usr + 0.00 sys = 2.67 CPU) @ 3745318.35/s (n=10000000)
defined: 3 wallclock secs (1.53 usr + 0.00 sys = 1.53 CPU) @ 6535947.71/s (n=10000000)
defined_smart: 3 wallclock secs (2.17 usr + 0.00 sys = 2.17 CPU) @ 4608294.93/s (n=10000000)
exists: 1 wallclock secs (1.33 usr + 0.00 sys = 1.33 CPU) @ 7518796.99/s (n=10000000)
एक प्रमुख ('एक्स') है कि मौजूद है करता है का उपयोग कर पता चलता है कि 'is_smart' के रूप में विजेता है।
Benchmark: timing 10000000 iterations of as is, as is_smart, defined, defined_smart, exists...
as is: 3 wallclock secs (2.76 usr + 0.00 sys = 2.76 CPU) @ 3623188.41/s (n=10000000)
as is_smart: 3 wallclock secs (1.81 usr + 0.00 sys = 1.81 CPU) @ 5524861.88/s (n=10000000)
defined: 3 wallclock secs (3.42 usr + 0.00 sys = 3.42 CPU) @ 2923976.61/s (n=10000000)
defined_smart: 2 wallclock secs (2.32 usr + 0.00 sys = 2.32 CPU) @ 4310344.83/s (n=10000000)
exists: 3 wallclock secs (2.83 usr + 0.00 sys = 2.83 CPU) @ 3533568.90/s (n=10000000)
वास्तव में मूल्य को पुनर्प्राप्त करने से सस्ता है? आखिरकार, जब टकराव पाता है तो उसे एक लिंक्ड सूची का पालन नहीं करना पड़ता है। – Frank
इस विशेष मामले में, हालांकि, "$ name" के लिए हैश कुंजी * ऑटोविविफिकेशन द्वारा नहीं बनाई जाएगी। केवल एक कुंजी नेस्टेड एक स्तर गहराई तक पहुंचने का प्रयास कर रहा है, जैसे कि "$ id = $ ids {$ name} {other}" "$ name" कुंजी बनाएगा। – trendels
@trendels सही लेकिन मुझे लगता है कि ओपी अधिक सरलीकृत था। फिर भी, मुझे यह इंगित करना चाहिए था। –