Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Beauty is in the eye of the beholder

by ChOas (Curate)
on Feb 20, 2001 at 17:42 UTC ( [id://59652]=perlmeditation: print w/replies, xml ) Need Help??

What is Beauty ?, I don't know, I want to look for beauty in code effeciency,
as well as how the code looks.

Example: I need know if a specific element is in a list, I could do:
print "Found it!\n" if (grep {/^I_am_looking_for_this$/o} @List);

Sweet, short, and simple...

Yet, I do not like it... I forgot to mention that my list consists of 100_000
elements, what if 'I_am_looking_for_this' was the second one ? ...

2nd approach:
my $Found=0; for (@List) { if (/^I_am_looking_for_this$/o) { $Found=1; last; }; }; print "Found it!\n" if $Found;
Hmmmmm... effective, though I don't like it, it's a hell of a lot of code,
but it will probably be faster than the first example.

Now, if I were gonna do this a lot more, I would prefer a sub:

sub IsInThere(@) { for (@_) {return 1 if /^I_am_looking_for_this$/o} return 0; }; print "Found it!\n" if IsInThere(@List);

I don't know what real beauty is, I know that I can like something I see, and reason
for efficiency...

I like to code... I like it a lot...

Thank you all for listening...

I would have used a hash by the way ;)

GreetZ!,
    ChOas

print "profeth still\n" if /bird|devil/;

Replies are listed 'Best First'.
Re: Beauty is in the eye of the beholder
by japhy (Canon) on Feb 20, 2001 at 18:15 UTC
    Yes, grep() is a bad idea here. And your regex, sadly, is an even poorer one. The FAQ warns you about this, believe it or not, in the same answer about how to determine if a list contains an element.

    I believe the List::Utils module offers a function called first() which looks like this:
    sub first (&@) { my $cref = shift; $cref->($_) and return $_ for @_; }
    So that it returns the first value in a list for which a chunk of code returns true:
    # get the first number found over 1000 $first_match = first { $_ > 1000 } @numbers;
    But if you do this a lot of times, you're kissing inefficiency on its ratty lips. Use a hash:
    my %seen; @seen{@array} = ();
    Now you can use the exists() test:
    if (exists $seen{blah}) { ... }
    Again, read the FAQ. Look for the keyword "contains".

    japhy -- Perl and Regex Hacker
      One thousand pardons, m'lord japhy, but you wrote:

      But if you do this a lot of times, you're kissing inefficiency on its ratty lips. Use a hash:

      In the oft-maligned name of pragmatism, I cobbled together the following brief, unscientific test:

      #!/usr/bin/perl -w use Benchmark; @List = ("aaaa" .. "zzzz"); print "Elements:", scalar @List, "\n"; sub first (&@) { my $cref = shift; $cref->($_) and return $_ for @_; } $t0 = new Benchmark; $first_match = first {$_ eq "zzzz"} @List; $t1 = new Benchmark; $td = timediff($t1, $t0); print "Found it! (sub)\n" if $first_match; print "sub took: ", timestr($td), "\n"; # Crufty way to figure out how big I am on a Linux box - /msg me with +improvements, please! -McD $size = (split(" ", `ps -hlp $$`))[6]; print "Size: $size\n"; $t0 = new Benchmark; my $Found=0; for (@List) { if ($_ eq "zzzz") { $Found=1; last; } } $t1 = new Benchmark; $td = timediff($t1, $t0); print "Found it! (scan)\n" if $Found; print "scan took: ", timestr($td), "\n"; $size = (split(" ", `ps -hlp $$`))[6]; print "Size: $size\n"; $t0 = new Benchmark; my %seen; @seen{@List} = (); $t1 = new Benchmark; $td = timediff($t1, $t0); if (exists $seen{"zzzz"}) { print "Found it! (hash)\n"; } print "hash took: ", timestr($td), "\n"; $size = (split(" ", `ps -hlp $$`))[6]; print "Size: $size\n";
      To make this a worst-case for the linear teams, I searched for the last item in the list.

      As it turns out, the least appealing code is the fastest - but while the hash approach may not be kissing performance inefficiency on it's ratty lips, it's certainly been caught in some kind of carnal embrace with memory inefficiency.

      Here are the results on my box:

      ./existance.pl
      Elements:456976
      Found it! (sub)
      sub took:  2 wallclock secs ( 1.49 usr +  0.01 sys =  1.50 CPU)
      Size: 58632
      Found it! (scan)
      scan took:  1 wallclock secs ( 0.40 usr +  0.00 sys =  0.40 CPU)
      Size: 58632
      Found it! (hash)
      hash took:  2 wallclock secs ( 0.90 usr +  0.15 sys =  1.05 CPU)
      Size: 88324
      
      Of course, we've strayed far from meditation and into experimentation. I'm sorry, what were we optimizing for again? :-)

      Peace,
      -McD

        You quoted me, and then didn't follow my lead. "But if you do this a lot of times, you're kissing inefficiency on its ratty lips."

        You performed these tests ONCE each. Use the first() function several times. Scan through the array several times. Create the hash ONCE, and use exists() many times.

        japhy -- Perl and Regex Hacker
        Here's my test. first() can be made faster by passing an array reference, not the array.
        (RESULTS) Elements:17576 sub took: 52 (51.14 usr + 0.00 sys = 51.14 CPU) scan took: 17 (13.85 usr + 0.00 sys = 13.85 CPU) hash took: 0 ( 0.17 usr + 0.13 sys = 0.30 CPU) (CODE) #!/usr/bin/perl -w use Benchmark; @List = ("aaa" .. "zzz"); print "Elements:", scalar @List, "\n"; @rand_list = map $List[rand @List], 1 .. 100; sub first (&@) { my $cref = shift; $cref->($_) and return $_ for @_; } $t0 = new Benchmark; for (@rand_list) { $rand_element = $_; $first_match = first {$_ eq $rand_element } @List; } $t1 = new Benchmark; $td = timediff($t1, $t0); print "sub took: ", timestr($td), "\n"; $t0 = new Benchmark; for (@rand_list) { $rand_element = $_; for (@List) { last if $_ eq $rand_element } } $t1 = new Benchmark; $td = timediff($t1, $t0); print "scan took: ", timestr($td), "\n"; $t0 = new Benchmark; my %seen; @seen{@List} = (); $t1 = new Benchmark; $td = timediff($t1, $t0); for (@rand_list) { 1 if exists $seen{$_} } print "hash took: ", timestr($td), "\n";


        japhy -- Perl and Regex Hacker
      ;)))

      As you might have read, I would have used a hash....

      I was trying to find an example of beauty/efficiency
      sad enough, that was the best I could come up with ;))

      I would have probably used 'eq' instead of the regex too ;)))

      GreetZ!,
        ChOas

      print "profeth still\n" if /bird|devil/;
        Well, an interesting feature of Perl is that by using its data structures, one can often make a structure representing some complex algorithm (like a hash being used to eliminate duplicates).

        japhy -- Perl and Regex Hacker
Re: Beauty is in the eye of the beholder
by Maclir (Curate) on Feb 21, 2001 at 02:39 UTC
    And remember, what is beautiful today, may be considered ugly tomorrow. (can anyone remember the fashion styles of the 1970's?) There has recently been the thread started by Tilly on Random thoughts on programming, where a number of monks shared their wisdom on good program design.

    If I were implementing such a "have I got that item in my list?" function, I would also include in the code the "key" to where in the list that item is, just in case I will want to do something to that item. Now, if we use a hash, then we get that:

    $my_hash{$key_value} = 'Stuff up the value real good';
    Otherwise, if I have a function that tells me whether the item is in the list, I would have the return value being a logical false if the item was not found, or the direct key to it if it was found. If you are doing a simple logical test, then returning a defined value is (should be) accepted as "true" (see page 20 - 21 "What is Truth" of the Camel book).

    If it wasn't first thing in the morning, I would attempt to hack a bit of code demonstrating this, but I am sure you all know what I mean here. The essence of what I am saying is that a good programmer looks ahead, and allows for the foreseeable future requirements.

    Updated: Stupid typo in code fragment fixed. I should finish my coffee before coding.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://59652]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-16 08:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found