ocehb: (Default)
ocehb ([personal profile] ocehb) wrote2006-05-19 09:15 am
Entry tags:

Поиск позиции элемента в массиве


1. 
my $i; for ($i = 0; $i < scalar @array; $i++) { last if ($array[$i] == $value); }


2. 
my $i = 0; foreach (@array) { last if ($_ == $value); $i++; }


3. 
my $i = 0; map { $_ == $value ? last : $i++ } @array; }


Проверка:

# perl -MBenchmark=timethese -de0
  DB<1> @array = map { int rand 10240 } 1..10240
  DB<2> $value = 6000
  DB<3> timethese (10_000,{'A' => q|my $i; for ($i = 0; $i < scalar @array; $i++) { last if ($array[$i] == $value); }|,\
                           'B' => q|my $i = 0; foreach (@array) { last if ($_ == $value); $i++; }|,\
                           'C' => q|my $i = 0; map { $_ == $value ? last : $i++ } @array;|})
Benchmark: timing 10000 iterations of A, B, C...
         A: 56 wallclock secs (46.91 usr +  0.02 sys = 46.93 CPU) @ 213.08/s (n=10000)
         B: 36 wallclock secs (31.43 usr +  0.01 sys = 31.44 CPU) @ 318.07/s (n=10000)
         C: 35 wallclock secs (35.03 usr +  0.00 sys = 35.03 CPU) @ 285.47/s (n=10000)



Post a comment in response:

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

If you are unable to use this captcha for any reason, please contact us by email at support@dreamwidth.org