I have a function that writes a bitmap string to a browser, which then prints it on screen. Currently this works by generating the correct values for each pixel individually and using the write(int fd, char *Buff, int NumBytes) function three times for every pixel, e.g.:
for (i = 0; i < IMAGE_HEIGHT; ++i)
{
for (j = 0; j < IMAGE_WIDTH; ++j)
{
blue = blue();
green = green();
red = red();
write(soc, &blue, 1);
write(soc, &green, 1);
write(soc, &red, 1);
}
}
I was wanting to optimize the code and figured that calling the write() function so many times is surely costing me something. So, the idea was to store all the values in a character array and then call the write function once:
write (soc, image_array, sizeof(image_array));
but am I going to have problems with the huge arrays (100’s of thousands/millions of elements)? Would just allocating to the heap solve this? I just wanted to make sure I’m not doing anything stupid.
Yes, the multiple writes will hurt you.
Rather than write each byte individually or allocate the entire thing, I suggest writing to a small buffer (perhaps a few KB) and writing that every time it fills up. That should give you a good performance gain for small memory cost.