Here's a snippet of some supplied (CS50) code that declares the same STRUCT 'triple', over and over again inside of a nested loop. Why is this okay? In my mind, it would be more efficient to declare the STRUCT 'triple' just above the scope of the nested loops and change the values each iteration.
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
.
for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
// iterate over pixels in scanline
for (int j = 0; j < bi.biWidth; j++)
{
// temporary storage
RGBTRIPLE triple;
// read RGB triple from infile
fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
// write RGB triple to outfile
fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
}
Efficiency at this level is the compiler's concern in most cases. The compiler may well reuse the same stack space for each RGBTRIPLE! (Although it doesn't have to.)
Putting the RGBTRIPLE within the smallest brace pair (scope) that needs it prevents you from accidentally, erroneously accessing that variable outside that scope, when the variable's contents may not be valid.
Still, are thousands of iterations of the same declaration is better than a single declaration right before the first loop?
Sure this is all right. Either way, a good compiler will not emit code having any performance difference.
What might make for a modest linear performance change would be to call fread()
less often.
for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++) {
RGBTRIPLE triple[bi.biWidth];
fread(triple, sizeof triple, 1, inptr);
fwrite(triple, sizeof triple, 1, outptr);
}
or even
RGBTRIPLE triple[biHeight][bi.biWidth];
fread(triple, sizeof triple, 1, inptr);
fwrite(triple, sizeof triple, 1, outptr);
Lots of factors go into coding consideration. Avoid focusing on micro optimizations such as these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With