简体   繁体   English

在 Delphi 中解释整数溢出的最佳方法是什么?

[英]What is the best way to account for integer overflow in Delphi?

I have a double value that will be passed to Round , and I need to make sure it won't overflow an Int64 .我有一个将传递给Rounddouble值,我需要确保它不会溢出Int64 If it would overflow, I just set the value to 0. What is the best way of doing this?如果它会溢出,我只需将值设置为 0。这样做的最佳方法是什么? 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.MinValueInt64.MaxValueInt64.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.我正在使用德尔福 10.3。

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.如果您希望value经常溢出 Int64,则第二个更好,否则,第一个会更好。

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.对于大多数用例,我会说#1 会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM