[Purdue-pm] Efficiency, was: my 2015-08-12 challenge problem solution

Rick Westerman westerman at purdue.edu
Sun Aug 9 08:18:04 PDT 2015

> Human time costs more than computer time.  I didn't bother to
> optimize the Perl 5 or Perl 6 solutions.

I think that is a dangerous concept to hold on to.  Certainly for one-off programs computer time generally does not matter over human time but if a person gets the idea that human time always trumps computer time then that person can get sloppy to the point that when does he write a production program said program performs poorly.   Thinking about order-N effects is, IMHO, always a good idea especially for large data sets.

In these ventures/experiments we try to explore the “many ways to do things” that Perl offers.   Some ways are more efficient than others.  I am not saying that we should optimize to the last little bit but we should explore and talk about ways to make our code more efficient.

For example — and this has nothing to do with your code — if I want the last element of parsed string there there are many ways to do that task:

my $data = ‘aaa:b:cccc’ ;

my ($one) = reverse grep { $_ } split ‘:’, $data ;

my @twoarr = split ‘:’, $data ;
my $two = $twoarr[-1] ;

my $pos   = rindex $data , ':' ;
my $three = substr($data, $pos + 1) ;

All three — $one, $two, $three — produce the string ‘cccc’ but they do so with increasing efficiency.   Once again not a biggie if the data set is small or if the program is being run once in a blue moon but — IMO — programmers who do not give thought to what they are doing when they write small programs will produce inefficient programs when speed does count for something.

BTW: I do not wish to hold myself up as a paradigm of always writing efficient code — I can be just as sloppy as the next person — but I do try to think of what is happening in the background — e.g., are unneeded anonymous arrays being produced? -- and the order-N effects.

BTW#2:  Anyone have an even more efficient way of getting the last element of a list contained in a string?  

BTW#3:  If I have time I’ll go through your Perl5 program and see if I can tease out inefficient code.  That could be instructive for all of us (and I hope not displeasing to you).  If nothing else this will give me an excuse to look at the code more closely — maybe I’ll learn something new and efficient.


More information about the Purdue-pm mailing list