|
String Performance
Part:
1
2
This chapter describes:
- How the two most common string functions perform under different environments.
- A Perl program to test the performance of substr() and index().
- A Java program to test the performance of substring() and indexOf().
Perl Test Program - SubstringTest.pl
I wrote the following program, SubstringTest.pl, in 1996 on a SunOS system to check
the performance of substr() and index() functions:
#- SubstringTest.pl
#- Copyright (c) 1996 by Dr. Herong Yang
#
($numChar, $numTest) = @ARGV;
$numChar = 10 unless $numChar;
$numTest = 1 unless $numTest;
$baseString = &setString($numChar);
$subString = &setString($numChar);
$startTime = time();
$numMatch = 0;
for ($i=0; $i<$numTest; $i++) {
$numMatch = &test();
}
$endTime = time();
$totalTime = $startTime - $endTime;
$averageTime = $totalTime/$numTest;
print("Number of tests = $numTest\n");
print("Number of characters = $numChar\n");
print("Number of matches = $numMatch\n");
print("Total time = $totalTime seconds\n");
print("Average time = $averageTime seconds\n");
exit;
sub setString {
local($size) = @_;
local $str = "";
local($i,$n,$c);
for ($i=0; $i<$size; $i++) {
$n = int(rand(96)) + 32;
$c = chr($n);
$str .= $c;
}
return $str;
}
sub test {
local($i,$j,$l);
local $str = "";
local $num = 0;
local $pos = -1;
for ($i=0; $i<$numChar; $i++) {
$l = $i+1;
for ($j=0; $j<$numChar-$i; $j++) {
$str = substr($subString,$j,$l);
$pos = index($baseString,$str);
$num++ if ($pos<0);
}
}
return $num;
}
The idea is to get two strings of the same length ramdonly, take all possible substrings
out of the first one, and try to match them in the other one with index().
Running this program with ActivPerl v5.6.1 on Windows 2000 system gave me:
>SubstringTest.pl 50 1000
Number of tests = 1000
Number of characters = 50
Number of matches = 1257
Total time = 8 seconds
Average time = 0.008 seconds
>SubstringTest.pl 100 1000
Number of tests = 1000
Number of characters = 100
Number of matches = 4976
Total time = 31 seconds
Average time = 0.031 seconds
>SubstringTest.pl 200 1000
Number of tests = 1000
Number of characters = 200
Number of matches = 19916
Total time = 137 seconds
Average time = 0.137 seconds
(Continued on next part...)
Part:
1
2
|