How would you do this EFFICIENTLY? By that I mean that, if it is done in a tight loop, it would execute fast. Simply checking against the same result done in long doesn't help - it's got the overhead of casting. Thank!
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
[Lambert Stein]: Simply checking against the same result done in long doesn't help - it's got the overhead of casting.
I think this attitude is impractical - anything you do here will be slower than a single unchecked addition or subtraction. You can't reject a possibility because you think it's slower than you'd like - you can only choose the best option you can come up with, whatever its speed. Don't reject an option unless you have a better one in mind.
Having said that, you may get faster results like this:
I have not tested this at all, however. I will be interested to hear if you find something faster. [ October 08, 2007: Message edited by: Jim Yingst ]
Ah, yes. I actually wrote a SafeMath class some years ago and worked through all these, testing carefully. But obviously I don't remember the results as well as I should. (And can't find the class on my computers; oh well.) That trick I used works well with multiplication and division, but not addition and subtraction. All, right, try this:
The condition can be written more compactly, but I've tried to arrange it for maximum efficiency. [ October 08, 2007: Message edited by: Jim Yingst ]
Lambert Stein
Greenhorn
Joined: Oct 30, 2006
Posts: 14
posted
0
So apparently it can't be done any other way than mine, right? Sure, I guess the previous post will work, but I was trying to avoid 'if' statements. Thanks to all, though!
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: int Addition/Subtraction Overflow Detection