java performance : Is storing a hashMap value in a variable redundant?

后端 未结 4 860
误落风尘
误落风尘 2020-12-20 07:35

my goal is to reduce memory usage. should I store a hashMap value in a variable if I need to use that value multiple times?

public void upcCheck() {
                 


        
4条回答
  •  失恋的感觉
    2020-12-20 08:28

    The first version is faster and more compact if only because you're not redundantly accessing the HashMap more than once.

    If you really are squeezed on memory you might look at dealiasing. It's not clear from your code snippet that it will help but the idea is if you have a large number of objects that can't or won't be modified you might be able to discard the duplicates.

    Before I get flamed by people ranting how this is unnecessary and a bad idea, I am taking your memory constraint issue at its word. This is not something anyone should normally concern themselves with.

    There may be more than one String object containing the value "0123456" floating around your program and if you pool them with String.intern()

    String productUPC=streamThing.readThing();
    productUPC=productUPC.intern();
    

    The effect of the second line is to replace the String read in with a 'canonical' String holding that value (from an internal pool). The effect will be to reduce (possibly massively) the number of String objects in play holding the value "0123456". If you read in 2000 products there may be 1000 Strings holding the same value. NB: Based on experience that most data is uneven and the most common value usually represents 50% of the population. The effect of that would be free up 999 String objects and (something like) give you 10K of memory back.

    I'll say again, that this isn't something you would normally do but it's more likely to save you space than worrying about the odd space taken up by a local variable.

    Here's a post about interning Strings. Read that and the article linked to see if this is for you.

    Is it good practice to use java.lang.String.intern()?

提交回复
热议问题