Java Performance – Storing a Value vs Calling Reference for Repeated Use

efficiencyjavaperformancereadability

I have an old habit of avoiding calling references multiple times, both for easier to read/maintain code, and for possible efficiency. But I'm wondering which is more efficient (memory, performance, both?).

For example when working with XML using a VTD parser

if( vn.toString( vn.getCurrentIndex() ).equalsIgnoreCase( "broken-label" ) == false )
        {
            do
            {   
                if( parentNode != null )
                {
                    currentNode = parentNode.addChildNode( vn.toString( vn.getCurrentIndex() ) );
                }
                else
                {
                    currentNode = new xmlNode( vn.toString(vn.getCurrentIndex()), null );
                    treeNodes.add( 0, currentNode );
                }

Does not store the value, perhaps saving some overhead for creating space to save a local variable and also lowering the burden on the garbage collector (assuming this section of code is repeated thousands of times in quick succession.

My habit of cleaner/efficient code would be to replace the above with the simple change of

String label = vn.toString( vn.getCurrentIndex();

if( label ).equalsIgnoreCase( "vsled-image" ) == false )
        {
            do
            {   
                if( parentNode != null )
                {
                    currentNode = parentNode.addChildNode( label ) );
                }
                else
                {
                    currentNode = new xmlNode( label, null );
                    treeNodes.add( 0, currentNode );
                }

While this is obviously easier to read and maintain. Are there any non-human benefits?

Best Answer

Function calls are expensive. In this example, by using that variable, you have eliminated four separate function calls. Each call puts stuff on the call stack, jumps the instruction pointer around, creates the rough equivalent of brand new variables anyway, etc. On many occasions, functions you call will create what really are new variables within their definitions as well.

So, yeah, in cases like this, it's better to just go ahead and make that extra variable up at the top. And if you're worried to death about it, and you're willing to sacrifice modularity and maintainability, you might set up the variable outside of the function's body, before the function is called, and then just reference it within the function.