Last active
October 12, 2015 18:58
-
-
Save hokamoto/4072938 to your computer and use it in GitHub Desktop.
Comparison between naive string concatenation and better one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#define SIZE 100000 | |
int main() { | |
int i; | |
char *buffer; | |
buffer = (char*) malloc(sizeof (char) * (SIZE + 1)); | |
clock_t t1, t2; | |
// algorhythm1 | |
memset(buffer, 0, sizeof (buffer)); | |
t1 = clock(); | |
for (i = 0; i < SIZE; i++) { | |
joinstring1(buffer, "a"); | |
} | |
t2 = clock(); | |
printf("naive: %.3f\n", (double) (t2 - t1) / CLOCKS_PER_SEC); | |
// algorhythm2 | |
memset(buffer, 0, sizeof (buffer)); | |
t1 = clock(); | |
int len = 0; | |
for (i = 0; i < SIZE; i++) { | |
len = joinstring2(buffer, "a", len); | |
} | |
t2 = clock(); | |
printf("modified: %.3f\n", (double) (t2 - t1) / CLOCKS_PER_SEC); | |
free(buffer); | |
return EXIT_SUCCESS; | |
} | |
joinstring1(char *dst, const char *src) { | |
// forward to the tail of dst | |
while (*(dst++) != '\0'); | |
dst--; | |
// join | |
while (*src != '\0') { | |
*(dst++) = *(src++); | |
} | |
} | |
int joinstring2(char *dst, const char *src, int dst_len) { | |
// forward to the tail of dst | |
dst += dst_len; | |
// join | |
int cnt = 0; | |
while (*src != '\0') { | |
*(dst++) = *(src++); | |
cnt++; | |
} | |
return dst_len + cnt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
naive: 189.135
modified: 0.016