Josh Bloch mentions using a local variable in double check idiom for possible performance improvement (EJ, 2nd ed. p284) and says the example code runs about 25% faster on his machine compared to that without a local variable. So the question is, why is it faster? In case of local variable version, it accesses the instance variable 3 times and in normal case it accesses the instance variable 4 times. Is this the reason behind ‘25%’ increase or are there any other reasons?
EDIT: 3 or 4 times access is only when the instance is first created. Thereafter, it’s 1 or 2 times.
EDIT2: check the accepted answer for this question to see the example code. I think this is for Java 6. How to solve the "Double-Checked Locking is Broken" Declaration in Java?
The basic thing is that accessing the
volatilevariable is slower, than accessing the local one. When you declare a local variable, you are basically caching the value of a volatile variable inside the method.In the normal (without a local variable) case you are accessing the volatile variable:
ifbefore thesynchronizedclauseifinside thesynchronizedclauseifwhere you assign a value to itreturnstatementNow, if you introduce a local variable, you only access the
volatilevariable three times:ifbefore thesynchronizedclauseifinside thesynchronizedclauseifwhere you assign a value to itYou do not access it in the
returnstatement, by returning the local variable, thus giving you a speed boost.