There are some problems with your code. The first is that you are calling strcat
on a destination array that has not been initialized. You need to set str[0] = '\0';
first.
The other problems are algorithmic. To know where to insert the target string, strcat
has to do strlen
or equivalent every time you call it. That means that it is stepping through O(n)
characters every time. That makes your algorithm ~O(n^2)
. Then you go and call strlen
again on every single character, with the same penalty. And keep in mind that the second loop is just setting the entire array to 'H'
.
If you want to copy a string 10000
times, you are better off pre-computing its length and just stepping along the buffer:
char str[100005];
const char *template = "HelloWorld";
int n = strlen(template);
char *p = str;
for(int i = 0; i < 10000; i++) {
strncpy(p, template, n);
p += n;
}
*p = '\0';
I am using strncpy
here because it avoids copying the terminating '\0'
of template
for every copy you make.
An alternative approach would be to use modulo division (which would probably be slower) to place the characters:
char str[100005];
const char *template = "HelloWorld";
int n = strlen(template);
int end = n * 10000;
for(int i = i; i < end; i++) {
str[i] = template[i % n];
}
Both approaches take a couple of orders of magnitude less time on my machine than your original loop, because they step through the array exactly once.
The final loop copies the previous character over and over into the remainder of the buffer. Since your buffer is filled with HelloWorld
, the loop copies 'H'
into every location. You can use memset
to do the same thing for you:
memset(str, 'H', 10000 * n);
The moral of the story is to avoid recalculating things that you can keep track of with a simple counter or pointer. If you want things to go fast, do as little work as possible.