Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: =?UTF-8?B?Sm9zaHVhIENyYW5tZXIg8J+Qpw==?= Newsgroups: comp.lang.java.programmer Subject: Re: Autoboxing and Performance ? Date: Tue, 20 Aug 2013 23:28:50 -0500 Organization: A noiseless patient Spider Lines: 37 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 21 Aug 2013 04:29:02 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="d8a043bbe1d5ad38eaab435e1d44bafa"; logging-data="17733"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX187pCjEUHcWCbl84IcWLcJikp57zpmvsTo=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.0 In-Reply-To: Cancel-Lock: sha1:zZ5zhqQTimN+rfcaTKNgYaLvjvQ= Xref: csiph.com comp.lang.java.programmer:25083 On 8/20/2013 5:15 AM, Peter Olcott wrote: > From Java A Beginner's Guide, Fifth Edition by Herbert Schildt, page 425: > > class AutoBox3 { > public static void main(String args[]) { > Integer iOb; > iOb = 99; > > // The following automatically unboxes iOb, > // performs the increment, and then reboxes > // the result back into iOb > ++iOb; > > It seems to me that all this unboxing and reboxing is a complete waste > of CPU time. It would make much more sense to provide an > Integer.Increment() member function that directly operates on the > contained data. Adding that would require that the class be mutable. However, mutability kills a lot of optimizations. For example, immutable classes get thread safety for free. In the specific case of boxed integers, the immutability allows the compiler to elide the boxing and unboxing in certain cases. So it's not at all clear that giving you that .increment function would actually make your code faster. > Why does Java waste so much CPU resources with its unboxing and reboxing > in cases such as this, and not simply provide member functions that > directly operate on the contained data? The optimizer in the Java VM is capable of eliminating boxes if it finds it doesn't need them, so it's likely not even wasting any CPU resources at all. Even if it can't eliminate the boxes, it can fast-path code into a branch-and-subtraction/addition for an unbox/box, respectively. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth