Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I make java Objects Null?

Let's say I'm iterating over an array of Objects i.e.

for (int r = 0; r < rows; r++) {
        for (int c = 0; c < columns; c++) {

            if (bricks[r][c] != null) {
                bricks[r][c].draw(gl)

If I at some point want to destroy the brick, should my remove() method nullify the object like :

private void remove(GameBrick obj) {
     for (int r = 0; r < rows; r++) {
        for (int c = 0; c < columns; c++) {
        if (bricks[r][c] != null){
        if (bricks[r][c] == obj) {
            bricks[r][c] = null;
        } 

Or should it rather set a flag boolean exists to false, and while iterating the objects, add a return or continue statement if bricks[r][c].exists == false ?

Currently I have my code based around nullifying object and null checks, but I later read about the Garbage Collector and that setting an object to null makes it run more often.

I want to know if this is true, and what I should do best to remove objects (if I even should).

like image 335
user717572 Avatar asked Dec 22 '22 01:12

user717572


1 Answers

but I later read about the Garbage Collector and that setting an object to null makes it run more often.

Nope, that would be pure hearsay. The best approach is to assume that the GC has been optimised to run as often as necessary to get the best balance between performance and memory usage.

Setting references to null is the way you signal to the GC that you no longer need the object. the GC doesn't have to do anything about it immediately.

Update

To tune the performance of an application, you have to measure the behaviour of the whole application - which means you have to write the whole application (or a very realistic end-to-end model of it) first. Micro-optimisation doesn't work.

So the best approach is to let the GC do what it is designed for - to make it easy for you to write clear, simple, easy-to-modify code thanks to automatic memory management. That way, when you have tested your app on the target machine/device and you can see where you need to tune performance, it will be easy to make the necessary changes without breaking anything.

Performance optimisation has to be driven by measurement. Measurement has to be done on a realistic prototype of the complete product. So in your first-pass implementation, concentrate on writing easy-to-modify code. Then measure, and put messy hacks into only the places where they are actually needed.

Bear in mind that they may need to be in different places depending on the device you are running on! On some devices, a hack applied in a specific spot may slow you down, whereas on another device it speeds you up. So you can't just blindly follow a rule everywhere in your code. You have to measure.

like image 128
Daniel Earwicker Avatar answered Jan 07 '23 23:01

Daniel Earwicker