kenics.net

Technical notes on perl, python, php, sql, cgi, c/c++, q/kdb+, unix/shell, revision control tools, data structures & algorithms, and their applications into web services and other various forms of software engineering.

perl performance optimization

 
######################################### 
####     perl performance topics     #### 
######################################### 
 
(ref) 
http://perldoc.perl.org/perlperf.html 
 
the usual suspects for performance bottleneck are sycall(noteably fileIO), function calls, and algorithms in general. 
any given operation, there are a few ways to do it; consider each option's underlying complexity. 
 
 
#### 
####   dynamic mem allocation 
#### 
 
Think in terms of C. 
 
-----------------------------// mem.pl 
 
#!/usr/bin/perl 
 
$str = "foo";    #  3 bytes malloc'ed 
$str .= "bar";   #  3 more bytes malloc'ed. 6 bytes in total, 
$str =~ s/foo//; #  3 bytes emptied, but note still 6 bytes allocated. 
$str = "";       #  all emptied by still 6 bytes allocated. 
undef $str;      #  finally 6 bytes are freed. 
 
 
#  now suppose we want $str .= "bar" type of operation a lot. 
#  newly allocating mem every time can be an overhead and possibly leads to fragmentation which also degrades performance. 
#  so we can try something like below initially. 
 
$str = "a" x 999;   # you adjust the number 999 according to the requirement of the expected subsequent ops. 
$str = ""; 
 
------------------------------ 
 
 
#### 
####   string concatination, manipulation 
#### 
 
 
 
#### 
####   function calls, stack, reference 
#### 
 
 
 
#### 
####    mem copy 
#### 
 
imagine adding a char into a string, (1) to the head, (2) to the middle, (3) to the end. 
obviously, (3) is most mem efficient. both (1)&(2) involve shifting the existing elems. 
 
-------------------------// substr.pl 
 
$str = "foobar"; 
 
substr($str,0,0) = "Z";   # Zfoobar 
substr($str,2,0) = "Z";   # foZobar 
substr($str,6,0) = "Z";   # foobarZ 
 
------------------------ 
 
 

  1. 2015-01-17 00:37:33 |
  2. Category : perl
  3. Page View:

Google Ads