3 ms·
Code should be written for humans and compiler should optimize the algorithm. If the compiler can't optimize properly then I think one should still write the or
by kirab 12y ago
Code should be written for humans and compiler should optimize the algorithm. If the compiler can't optimize properly then I think one should still write the original algorithm into an adjacent comment.
So I would've rather written:
int padded_size(int size)
int remainder = (size % 2048);
bool needsPadding = (remainder > 0);
if (!needsPadding) {
return size;
}
return size + (2048 - remainder);
}
- scott_s 12y agoBikeshed time! I feel that the bool adds complexity to the logic. I would rather just use an actual comment to indicate what the condition is for: int padded_size(int size) { int remainder = size % 2048; // do we even need padding? if (remainder == 0) { return size; } return size + (2048 - remainder); }
- to3m 12y agoReally? This is like using addition in a loop to multiply numbers, I'd say. Nothing wrong with the result, it's just a weird, roundabout way of doing it. Do (size+2047)/2048*2048 if you really can't stand the bitwise operations, though in most cases the fact it's a power of two is important and avoiding bitwise operations obscures that.
- scott_s 12y agoI consider (size+2047)/2048*2048 to be an optimization. If I was to explain the process to another person, I would use the algorithm I wrote above; I would literally say, "If size is already a multiple of 2048, just use that, otherwise, add on enough to make it a multiple of 2048."