动态的Java整数/长溢出检查与性能 [英] Dynamic Java integer/long overflow checking versus performance

查看:155
本文介绍了动态的Java整数/长溢出检查与性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当理论性的问题,因此,尽管语言是专门的Java,任何通用的解决方案就足够了。

This is a rather theoretical question, so while the language is specifically Java, any general solution will suffice.

假设我想写一个平凡的阶乘函数:

Suppose I wanted to write a trivial factorial function:

long factorial(int n)
{
    //handle special cases like negatives, etc.

    long p = 1;
    for(int i = 1; i <= n; i++)
    {
        p = p * n;
    }
    return p;
}

但现在,我也想检查阶乘溢出(不只是硬编码一个MAX_FACTORIAL_PARAMETER或东西等)。一般检查乘法期间溢出很简单,只要检查结果,对原来的输入,但在这种情况下,由于溢出可能发生在任何一点上,这将是相当昂贵的,以在每一个循环进行以上的分部和比较

But now, I also want to check if the factorial overflows (without simply hard coding a MAX_FACTORIAL_PARAMETER or something of the like). In general checking for overflow during multiplication is as simple as checking the result against the original inputs, but in this case, since overflow can occur at any point, it would be rather expensive to perform more divisions and comparisons in every single loop.

接下来的问题,是双重的 - 有什么办法来解决溢出的阶乘问题,不检查乘法溢出的每一步或硬编码的最大允许参数

The question then, is twofold--is there any way to solve the factorial problem of overflow without checking for multiplication overflow at every step or hard coding a maximum allowed parameter?

而在一般情况下,我应该怎么办法涉及循环/递归的许多阶段,可以在每一个阶段静默失败,而不通过引入昂贵的层层把关影响性能的问题?

And in general, how should I approach problems that involve many stages of iteration/recursion that could silently fail at every stage without compromising performance by introducing expensive checks at each?

推荐答案

尽管Java不帮你这个,当然有语言的帮助溢出。例如,C#提供了检查关键字。下面,这个功能可能使用的硬件支持,在溢出标志的形式。

While Java does not help you with this, there certainly are languages that help with overflow. For example, C# provides the checked keyword. Underneath, this feature probably uses hardware support in the form of the overflow flag.

这篇关于动态的Java整数/长溢出检查与性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆