NewStudent
NewStudent

Reputation: 303

Which of these two Java codes is faster?

Both theoratically and practically which code is faster:

class ABC{
    File file;

    void method(){   
        file = new File();
    }
}

or

class ABC{

    void method(){
        File file = new File();
    }
}

where class ABC is instantiated only once. But the method() for that instance is called multiple times. Note: I KNOW the speed actually is irrelevant in this case.

Upvotes: 1

Views: 98

Answers (2)

NewStudent
NewStudent

Reputation: 303

At last I got a direction. Not on stackoverflow but on Quora. Check the answer by Cameron Purdy here..https://www.quora.com/How-much-time-does-it-take-to-access-an-object-and-variable-in-Java-And-whats-the-ratio-between-them

Upvotes: 0

Philipp
Philipp

Reputation: 69663

The performance difference is unlikely to matter much.

In the first version , there will be a valid reference to the File object around until the next call to method, but the previous object will still need to be garbage-collected after it got replaced. In the second version, the File object is orphaned the moment method is finished and can be garbage-collected.

So the first version means you will always have at least one non-collectable File object staying around in memory as long as the instance of ABC exists. This is unlikely to be much of a problem, though, unless File consumes a non-negligible amount of memory (it only contains the path and name of the file. Buffering file content is BufferedReader's job) and you keep a lot of ABC instances around.

What you should be worrying about, though, is code clarity. The general rule is that every variable should have the smallest scope possible. When it can be a local variable, then it should be local variable. The reason is that the smaller the scope, the less code might possibly affect its value, which makes the application easier to debug. When you encounter a bug where file suddenly hasn't got the value you expect it to have, you only need to examine that one method, not the whole class.

Upvotes: 4

Related Questions