Someone told me that it is saving memory to use numbers directly instead of static final int fields, is that true?

StackOverflow https://stackoverflow.com/questions/10512175

Question

In my Android project, there are many constances to represent bundle extra keys, Handler's message arguments, dialog ids ant etc. Someone in my team uses some normal number to do this, like:

handler.sendMessage(handler.obtainMessage(MESSAGE_OK, 1, 0));
handler.sendMessage(handler.obtainMessage(MESSAGE_OK, 2, 0));
handler.sendMessage(handler.obtainMessage(MESSAGE_OK, 3, 0));

in handler:

switch (msg.arg1) {
case 1:
    break;
case 2:
    break;
case 3:
    break;
}

he said too many static final constances cost a lot of memory. but i think his solution makes the code hard to read and refactor.

I have read this question and googled a lot and failed to find an answer. java: is using a final static int = 1 better than just a normal 1?

I hope someone could show me the memory cost of static finals.

Sorry for my poor English.

Était-ce utile?

La solution

Technically, he is right - static int fields do cost some additional memory.

However, the cost is negligible. It's an int, plus the associated metadata for the reflection support. The benefits of using meaningfull names that make your code more readable, and ensure that the semantic of that number is well known and consistent evewhere it is used, clearly outweight that cost.

You can do a simple test. Write a small application that calls handler.sendMessage 1000 times with different number literal, build it and note down the size of the .dex file. Then replace the 1000 literals with 1000 static int consts, and do the same. Compare the two sizes and you will get an idea of the order of magnitude of additional memory your app will need. (And just for completeness, post the numbers here as comment :-))

Autres conseils

You shouldn't bother to change it to literals, it will make your code less readable and less maintainable.

In the long run you will benefit from this "lose of memory"

It saves a very small amount of memory - basically just the extra metadata required to record the extra constant in the relevant class and refer to it from other classes.

It is NOT worth worrying about this, unless you are extremely memory constrained.

Using well-named static final constants rather than mysterious magic numbers is much better for your code maintainability and sanity in the long run.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top