</source>
The ''strcat'' function looksis innocious enough, andunless it is, as long as you don't call itcalled '''repeatedly''' to build a large string.
SoHere lets examineis an example of how '''not''' to use ''strcat'':
<source lang="c">
// builds a 1Meg1 Megabyte string of "word, word, word, ....";
void testPerformanceOfStrcat() {
final int BUFFER_SIZE = 1024*1024;
char word[] = "word";
char buffer[BUFFER_SIZE] = "";
while( strlen(buffer) < BUFFER_SIZE-strlen(word) ) { // <-- LUDICROUSLY EXPENSIVE
if(*buffer) strcat(buffer, ", "); // <-- LUDICROUSLY EXPENSIVE
strcat(buffer, word); // <-- LUDICROUSLY EXPENSIVE
}
}
</source>
The estimated cost of ''testPerformanceOfStrcat'' is:
* NOTE: I am ignoring "ancillaryAncillary expensescosts" like the cost of making a function call are ignored.
* The string "word, " is 6 characters in length.
* The number of times through the loop is int(1024*1024/6) = 174,762 // strlen("word, ")==6
* The costnumber of ''strlen(buffer)''times inthrough the ''while'' conditionloop is [[Fibonacci_number|fib]]int(174,7621024*1024/6) = 15174,270,965,703762
* The cost of finding the end of the ''strlen(buffer (again)'' in the ''strcat(buffer, ", ")while'' condition is [[Fibonacci_number|fib]](174,762) = 15,270,965,703 (again)cycles.
* The cost of finding the -end -of -the -buffer (again) in ''strcat(buffer, word", ")'' is 15,270,965,703 (again)cycles.
* The cost of finding the-end-of-the-buffer in ''strcat(buffer, word)'' is 15,270,965,703 cycles.
* So theThe TOTAL COST of ''testPerformanceOfStrcat'' is 15,270,965,710 * 3 = 45,812,897,130 or about 45 billion clock tickscycles.
* 45 billion cycles at 2 billion cycles per second (my CPU is 2.01GHz) is about 22 seconds.
* 45 billion cycles on a 2GHz CPU is about 22 seconds, which is totally unaceptable.
* 22 seconds to build a buffer! Ouch !!!!! !!!!! !!!!! !!!!! !!
== The Solution ==
|