Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Travers Naran Newsgroups: comp.lang.java.programmer Subject: Re: Java left shift and right shift operators. Date: Tue, 26 Apr 2011 22:40:35 -0700 Organization: A noiseless patient Spider Lines: 45 Message-ID: References: <295e16b3-2ed8-4529-bfb0-1cc26ed93ad6@d26g2000prn.googlegroups.com> <188cz6ta97kkm$.dlg@kimmeringer.de> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 27 Apr 2011 05:40:39 +0000 (UTC) Injection-Info: mx03.eternal-september.org; posting-host="mZwD6WroWf8ZiutQVyui4A"; logging-data="19413"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/bcwhJq/3oknkdMfog5DVS" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.15) Gecko/20110303 Lightning/1.0b2 Thunderbird/3.1.9 In-Reply-To: Cancel-Lock: sha1:fRnJByJRhhfHqyK9KFq+WvX5nQ8= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3292 On 26/04/2011 9:32 AM, Sanny wrote: > I have computed and found "if statments" take 20-50 times longer than > basic arithmetic operations. So I wanted to replace if condition by > some arithmetics/ Maths. This is why I think assembly language should be mandatory in schools. :-) An if statement gets translated into something like (using a pseudo-assembly for readability): ;; if (b > 0) return a << b else return a >> -b compare b to 0 jump-less-than to L1 a := a << b jump L2 L1: b := -b a := a >> b L2: return ;; result in a It's the jump that's adding the time. But on an x86, that kind of instruction can be entirely cached and the Intel/AMD processors can perform predictive branching to speed up this bit of code. The only way you should be getting 20-50 times longer is if you aren't using any sort of optimizing run-time. Example: running always as byte code without compiling. But usually this kind of if-checking and bit-twiddling is so fast that it's not worth optimizing beyond a single statement. What are you coding that makes this the most expensive calculation in your program? OFF-TOPIC ========= Bonus Question: If branching is "20-50 times longer" than any of the operations (negation or shifting), how could you re-write this assembly to use a single branch statement? Extra Bonus: Using your favorite processor instruction set, come up with a fast implementation of: if (b > 0) return a << b; else return a >> -b;