Article 6E780 Ways to test for efficiency in C?

Ways to test for efficiency in C?

by
jmgibson1981
from LinuxQuestions.org on (#6E780)
I'm curious is this idea would improve overall memory consumption.

This is how i did it first
Code:FILE * file = fopen("name.txt", "r");

char buffer[256];

for (int i = 0; i <= 1000; i++) {
if (fgets(buffer, sizeof(buffer) - 1, file) {
// do stuff to file, extract info, whatever
}
}But wondered if unused allocated buffer space was a waste of mem while looping. So came up with this function to return memory exactly as to the found string. calling this in place of fgets directly in the function above. Above the buffer is in place as long as the function is running, looping. Below it creates it only long enough to get an exact malloc out of it. Use it then free before continuing the loop.

Code:char * fgets_mem_alloc(FILE * file)
{
assert(file);
char buffer[MAX_BUFFER] = {'\0'};

if (fgets(buffer, RETURN_BUFFER, file)) {
char * retval = allocate_string_mem(buffer);
return(retval);
}
return(NULL);
}For reference

Code:char * allocate_string_mem(const char * str)
{
assert(str);
char * retstr = (char*)malloc(strlen(str) * sizeof(char) + 1);
strcpy(retstr, str); assert(retstr);
return(retstr);
}Just curious if this is worth doing? Or... am I splitting to many hairs here? Does the cpu overhead > the memory savings??? I just don't know.

Can also add an int argument to specify buffer size for each set of loops or however one uses it.
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments