Laurent Hinoul

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” - John F. Woods

Memory optimalization in Java – tips and tricks

The memory can be filled very quickly whe you use many objects. That’s why it is necessary to think where you create your objects and what kind of objects you create.

Long vs long or Integer vs int

Long is the object type of long. It’s possible to create Long with the value null. A long is a number of 64 bits. So it’s no object but just a number that require an valid number or 0 (it cannot be null).

The same matters for Integer vs int. An Integer is an object and an int is a 32-bit number.

When you just need numbers, it’s better to use a long or int. Somethimes numbers in a database are null, then it is required to use a Long or Integer otherwise you get a NullPointerException.

A Long or Integer vs a long or int take needs more memory.

Creating objects in a loop

There’s nothing so bad then creating objects in a for-, while- or do-while- loop. Every object you create in a loop will be recreated every time the loop loops and all these objects will be saved in the memory. If you have a loop that loops a 100 times, and you create an object inside that loop, you get 100 new objects.

In the example above, you will generate 100 String objects. Each string will recreated an saved in the memory. An optimalization can you see below.

In this case, the String object will only be created once. Now, the loop will not recreate a new String-object, but will overide the object. So in this case you only have 1 object.

Leave a Reply