Home > Back-end >  What is the best way to account for integer overflow in Delphi?
What is the best way to account for integer overflow in Delphi?

Time:07-16

I have a double value that will be passed to Round, and I need to make sure it won't overflow an Int64. If it would overflow, I just set the value to 0. What is the best way of doing this? I thought about two ways:

  1. Handle the exception
try
  rounded := Round(value);
except
on E: EInvalidOp do
  rounded := 0;
end;
  1. Compare against Int64.MaxValue and Int64.MinValue
if (CompareValue(value, Int64.MaxValue) <> GreaterThanValue) and (CompareValue(value, Int64.MinValue) <> LessThanValue) then
  rounded := Round(value)
else
  rounded := 0;

I'm wondering what is the best approach to handle this problem. Performance is a concern for me. I'm using Delphi 10.3.

CodePudding user response:

If your main concern is performance, which is the best is "It depends".

If you expect value to overflow an Int64 often, the 2nd one is better, otherwise, the first one would be better.

The first one will be slightly faster every time it doesn't raise an exception and much slower everytime it does.

For most use cases, I'd say #1 would be faster.

  • Related