views:

134

answers:

3

Update: I'm going to leave it as is: The performance hit of a exception (very rare) is better than the probably performance hit for checking on each operation (common)


I'm trying to support an "EstimatedRowCount" that in one case would be the product of two sub-cursors that are joined together:

estimatedRowCount = left.EstimatedRowCount * right.EstimatedRowCount;
return estimatedRowCount;

Of course, if left and right are big enough, this will throw an OverflowException.

Here, I don't really care if estimatedRowCount is 100% accurate, just big enough to know that this cursor is holding a lot of data.

Right now, I'm doing this:

// We multiply our rowcount
Int64 estimRowCount = 0;
try
{
    estimRowCount = leftRowCount * rightRowCount;
}
catch (OverflowException)
{
    // Ignore overflow exceptions
    estimRowCount = Int64.MaxValue;
}

return estimRowCount;

Is there a better way to test for overflow operations so I don't have to do the try{}catch to guard?

+3  A: 

Your solution seems quite reasonable. Is there something specific you want to optimize? Does that product cause the overflow condition so frequently that you're worried about the performance hit of the exception handling?

(Just simple food for thought, if leftRowCount and rightRowCount are Int32, not Int64, then your product cannot overflow your Int64 estimRowCount lvalue.)

JMD
Everything is Int64. And this is probably "premature optimization" from learning from where the belief was "avoid hits for exception handling" if you could.
Eli
+4  A: 
shahkalpesh
So the question now is if it would be more efficient to check this for each calculation than dealing with the exceptions for the misses.
Eli
Not sure about that. But why do you worry about small things like this one?
shahkalpesh
I'm sure he's worried about small things like this one because if this is run in a tight loop that small thing becomes a big thing. But I like your suggestion too. I'm tempted to test the two variants with a high precision timer out of curiosity's sake.
JMD
+4  A: 

This sounds like a good use case for the 'unchecked' keyword.

To use, simply wrap your assignment in an 'unchecked' block:

Int64 estimRowCount = 0;
unchecked
{
    estimRowCount = leftRowCount * rightRowCount;
}

Then test to see if the result is negative - if it is, it overflowed:

if (estimRowCount > 0) estimRowCount = Int64.MaxValue;

You'll need to ensure in this case that neither leftRowCount nor rightRowCount can be negative, but given the context I don't think that'll occur.

Erik Forbes
This is one of those obscure language features that you never know about until you need it. =P
Erik Forbes