Have written 2 implementations of a program that should copy words to an output buffer and print the information out. I’m looking to optimise my program wrt operation time (algorithmic complexity).
/*cat implementation*/
#include <stdio.h>
#include <string.h>
char command_string[2][70] = {
"Henry",
"Julie",
};
int main()
{
char output_transmit_buffer[255];
int counter = 0;
while (1)
{
char *command = command_string[counter];
strcat (output_transmit_buffer, command);
printf ("%s\r\n", output_transmit_buffer);
//clearing output buffer
memset (output_transmit_buffer, 0, sizeof (output_transmit_buffer));
if (counter == 1)
{
return 0;
}
counter++;
}
return 0;
}
/*copy implementation*/
#include <stdio.h>
#include <string.h>
char command_string[2][70] = {
"Henry",
"Julie",
};
int main()
{
char output_transmit_buffer[255];
int counter = 0;
while (1)
{
char *ptr = output_transmit_buffer;
strcpy(ptr, command_string[counter]);
ptr += strlen(command_string[counter]);
printf("%s\r\n",output_transmit_buffer);
memset (output_transmit_buffer, 0, sizeof (output_transmit_buffer));
if (counter == 1)
{
return 0;
}
counter++;
}
return 0;
}
Which implementation is better? Is there a better implementation for MCU specific applications.
>Solution :
Both implementations have room for optimization. For MCU specific applications you should minimize unnecessary operations and optimize memory usage.
In you current implementations, strcat() has a time complexity of O(n+m), whereas, strcpy() and strlen() both have a time complexity of O(n). And you are clearing the output buffer after each iteration, which is not needed.
You can directly copy element from source to destination as below, although the copy makes no sense in your code (but it might be the case that you are using it some where else and you have just posted it as an example).
char *src = command_string[counter];
char *dst = output_transmit_buffer;
while (*src != '\0') {
*dst++ = *src++;
}
*dst = '\0';
printf("%s\r\n", output_transmit_buffer);
Also there is an issue with your counter athe you have to fix.
Comparison:
*dst++ = *src++ is efficient for small strings or when you know the exact number of characters to copy and it is commonly used in situations where memory and processing resources are limited, such as in embedded systems.
strcpy() typically performs well for larger strings or when the length of the string is unknown.