Search code examples
cconditional-operator

Would it be better to use fseek + ternary or an IF?


fseek( pChunk, (iCurChar < 31) ? ftell(pChunk)+((31-iCurChar)+1) : ftell(pChunk), 0 );

If the condition is not met we shouldn't move anywhere in the file. Which would go easier on the resources: having this ternary, or making an if that doesn't do basically nonsensical "fseek( ftell() )"?

I think the difference on modern machines is pretty much negligible but I'm really not sure what I should go for. The resource management is pretty important here so I would go for as little as possible, even if it's negligible.

I looked at what people say about them and some of the opinions differ. This case is pretty unique, I think, because there's also an extra operation in play with the ternary (the fseek to ftell). I don't know how big of a difference it will be and I have no experience in benchmarking whatsoever.


Solution

  • Although proclamations about code style are quite often subjective matters of opinion, I feel pretty confident in saying that the form

    if(iCurChar < 31)
        fseek(pChunk, (31-iCurChar) + 1, SEEK_CUR);
    

    would be unarguably preferable in every way. The ternary operator has its uses, but this isn't one of them.

    In general, the ternary operator is useful when you need to do something conditionally, but in a context where for whatever reason an if statement is not an option. But here, in deciding whether to call fseek or not, an ordinary if statement is definitely an option — it's the preferable option!

    There's nothing to be gained by calling fseek unconditionally and then, via the "false" branch of your ternary operator, contriving to have that fseek call sometimes not do anything.

    fseek is a fast call already, since basically all it does is adjust pointers or offsets into the file being read. So there's almost no percentage in trying to speed up a call to fseek. It's not clear what slim advantage you might have imagined could be gained by using the ternary operator (and some unnecessary ftell calls) in this way, but I can tell you that the advantage is not "slim"; it is nonexistent (or negative). Even in the most resource-constrained environment, the clean-and-obvious form should be fine.