java - creating distinct variables vs 1 variable for multiple values? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Create ArrayList from arrayHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java

Flash light on something

What does 丫 mean? 丫是什么意思?

Putting class ranking in CV, but against dept guidelines

What is the difference between a "ranged attack" and a "ranged weapon attack"?

The Nth Gryphon Number

Is multiple magic items in one inherently imbalanced?

What does Turing mean by this statement?

Co-worker has annoying ringtone

What is Adi Shankara referring to when he says "He has Vajra marks on his feet"?

What are the discoveries that have been possible with the rejection of positivism?

Why does 14 CFR have skipped subparts in my ASA 2019 FAR/AIM book?

How to pronounce 伝統色

How would a mousetrap for use in space work?

How long can equipment go unused before powering up runs the risk of damage?

How does light 'choose' between wave and particle behaviour?

Is there public access to the Meteor Crater in Arizona?

Significance of Cersei's obsession with elephants?

Is it possible for SQL statements to execute concurrently within a single session in SQL Server?

Antipodal Land Area Calculation

Customizing QGIS plugins

How to write capital alpha?

Dyck paths with extra diagonals from valleys (Laser construction)

What would you call this weird metallic apparatus that allows you to lift people?

Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?



java - creating distinct variables vs 1 variable for multiple values?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Create ArrayList from arrayHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-2















I have some code which is like:



String country = null;
country = getEuropeanCountry(); //Germany
//after few lines of code
country = getAsianCountry(); //Japan
//after few more lines
country = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to the same variable "country"*/


I have this kind of usage in most of my code.



For some reason, my application throws "Error java.lang.OutOfMemoryError: GC overhead limit exceeded".
So I tried with VM argument: -XX:-UseGCOverheadLimit
Then my app ran successfully but I noticed that it is consuming more memory (I had to set -Xmx to 5g or 6g; otherwise I get: out of memory error).



I checked my app and there are no memory leaks. But most of my code has the similar code that I posted above.



Can anyone tell me if it is beneficial for memory management if I refactor the above code to:



String europeanCountry = getEuropeanCountry(); //Germany
//after few lines of code
String asianCountry = getAsianCountry(); //Japan
//after few more lines
String northAmericanCountry = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to a different String variable*/


I can't use collections. I mean, in general, which way is better to use heap space and garbage collector efficiently?










share|improve this question



















  • 1





    Mmmh you must be doing something really wrong to have a GC overhead limit error. Are you sure you checked your application thoroughly?

    – LppEdd
    Mar 8 at 21:50












  • @LppEdd do you have any idea where should I start my diagnostics?

    – The Guest
    Mar 8 at 21:52











  • That's a tough question. How big is your codebase?

    – LppEdd
    Mar 8 at 21:53











  • Its a smaller one. Contains 2 to 3 service classes (each up to 1000 lines) and 2 to 3 dao classes and 1 main and model classes.

    – The Guest
    Mar 8 at 21:56











  • What do these methods execute behind the scene?

    – LppEdd
    Mar 8 at 21:59

















-2















I have some code which is like:



String country = null;
country = getEuropeanCountry(); //Germany
//after few lines of code
country = getAsianCountry(); //Japan
//after few more lines
country = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to the same variable "country"*/


I have this kind of usage in most of my code.



For some reason, my application throws "Error java.lang.OutOfMemoryError: GC overhead limit exceeded".
So I tried with VM argument: -XX:-UseGCOverheadLimit
Then my app ran successfully but I noticed that it is consuming more memory (I had to set -Xmx to 5g or 6g; otherwise I get: out of memory error).



I checked my app and there are no memory leaks. But most of my code has the similar code that I posted above.



Can anyone tell me if it is beneficial for memory management if I refactor the above code to:



String europeanCountry = getEuropeanCountry(); //Germany
//after few lines of code
String asianCountry = getAsianCountry(); //Japan
//after few more lines
String northAmericanCountry = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to a different String variable*/


I can't use collections. I mean, in general, which way is better to use heap space and garbage collector efficiently?










share|improve this question



















  • 1





    Mmmh you must be doing something really wrong to have a GC overhead limit error. Are you sure you checked your application thoroughly?

    – LppEdd
    Mar 8 at 21:50












  • @LppEdd do you have any idea where should I start my diagnostics?

    – The Guest
    Mar 8 at 21:52











  • That's a tough question. How big is your codebase?

    – LppEdd
    Mar 8 at 21:53











  • Its a smaller one. Contains 2 to 3 service classes (each up to 1000 lines) and 2 to 3 dao classes and 1 main and model classes.

    – The Guest
    Mar 8 at 21:56











  • What do these methods execute behind the scene?

    – LppEdd
    Mar 8 at 21:59













-2












-2








-2








I have some code which is like:



String country = null;
country = getEuropeanCountry(); //Germany
//after few lines of code
country = getAsianCountry(); //Japan
//after few more lines
country = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to the same variable "country"*/


I have this kind of usage in most of my code.



For some reason, my application throws "Error java.lang.OutOfMemoryError: GC overhead limit exceeded".
So I tried with VM argument: -XX:-UseGCOverheadLimit
Then my app ran successfully but I noticed that it is consuming more memory (I had to set -Xmx to 5g or 6g; otherwise I get: out of memory error).



I checked my app and there are no memory leaks. But most of my code has the similar code that I posted above.



Can anyone tell me if it is beneficial for memory management if I refactor the above code to:



String europeanCountry = getEuropeanCountry(); //Germany
//after few lines of code
String asianCountry = getAsianCountry(); //Japan
//after few more lines
String northAmericanCountry = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to a different String variable*/


I can't use collections. I mean, in general, which way is better to use heap space and garbage collector efficiently?










share|improve this question
















I have some code which is like:



String country = null;
country = getEuropeanCountry(); //Germany
//after few lines of code
country = getAsianCountry(); //Japan
//after few more lines
country = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to the same variable "country"*/


I have this kind of usage in most of my code.



For some reason, my application throws "Error java.lang.OutOfMemoryError: GC overhead limit exceeded".
So I tried with VM argument: -XX:-UseGCOverheadLimit
Then my app ran successfully but I noticed that it is consuming more memory (I had to set -Xmx to 5g or 6g; otherwise I get: out of memory error).



I checked my app and there are no memory leaks. But most of my code has the similar code that I posted above.



Can anyone tell me if it is beneficial for memory management if I refactor the above code to:



String europeanCountry = getEuropeanCountry(); //Germany
//after few lines of code
String asianCountry = getAsianCountry(); //Japan
//after few more lines
String northAmericanCountry = getNorthAmericanCountry(); //Canada
/*and the code follows by assigning a different country value to a different String variable*/


I can't use collections. I mean, in general, which way is better to use heap space and garbage collector efficiently?







java memory-management






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 22:01









LppEdd

10k31749




10k31749










asked Mar 8 at 21:46









The GuestThe Guest

449624




449624







  • 1





    Mmmh you must be doing something really wrong to have a GC overhead limit error. Are you sure you checked your application thoroughly?

    – LppEdd
    Mar 8 at 21:50












  • @LppEdd do you have any idea where should I start my diagnostics?

    – The Guest
    Mar 8 at 21:52











  • That's a tough question. How big is your codebase?

    – LppEdd
    Mar 8 at 21:53











  • Its a smaller one. Contains 2 to 3 service classes (each up to 1000 lines) and 2 to 3 dao classes and 1 main and model classes.

    – The Guest
    Mar 8 at 21:56











  • What do these methods execute behind the scene?

    – LppEdd
    Mar 8 at 21:59












  • 1





    Mmmh you must be doing something really wrong to have a GC overhead limit error. Are you sure you checked your application thoroughly?

    – LppEdd
    Mar 8 at 21:50












  • @LppEdd do you have any idea where should I start my diagnostics?

    – The Guest
    Mar 8 at 21:52











  • That's a tough question. How big is your codebase?

    – LppEdd
    Mar 8 at 21:53











  • Its a smaller one. Contains 2 to 3 service classes (each up to 1000 lines) and 2 to 3 dao classes and 1 main and model classes.

    – The Guest
    Mar 8 at 21:56











  • What do these methods execute behind the scene?

    – LppEdd
    Mar 8 at 21:59







1




1





Mmmh you must be doing something really wrong to have a GC overhead limit error. Are you sure you checked your application thoroughly?

– LppEdd
Mar 8 at 21:50






Mmmh you must be doing something really wrong to have a GC overhead limit error. Are you sure you checked your application thoroughly?

– LppEdd
Mar 8 at 21:50














@LppEdd do you have any idea where should I start my diagnostics?

– The Guest
Mar 8 at 21:52





@LppEdd do you have any idea where should I start my diagnostics?

– The Guest
Mar 8 at 21:52













That's a tough question. How big is your codebase?

– LppEdd
Mar 8 at 21:53





That's a tough question. How big is your codebase?

– LppEdd
Mar 8 at 21:53













Its a smaller one. Contains 2 to 3 service classes (each up to 1000 lines) and 2 to 3 dao classes and 1 main and model classes.

– The Guest
Mar 8 at 21:56





Its a smaller one. Contains 2 to 3 service classes (each up to 1000 lines) and 2 to 3 dao classes and 1 main and model classes.

– The Guest
Mar 8 at 21:56













What do these methods execute behind the scene?

– LppEdd
Mar 8 at 21:59





What do these methods execute behind the scene?

– LppEdd
Mar 8 at 21:59












2 Answers
2






active

oldest

votes


















1














For the question " I mean, in general, which way is better to use heap space and garbage collector efficiently?"



Lets look at the String implementation e.g. jdk8 https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java



public final class String

implements java.io.Serializable, Comparable<String>, CharSequence {

/** The value is used for character storage. */

private final char value[];


So it is a final character array - it cannot be reasigned or changed. So it is generated on the heap in your method and is never changed - only a reference(a name) is generated.



To make no mistake lets also look at the constructor of a String (doing smth. like eg. "newString = new String(otherString)":



public String(String original) 

this.value = original.value;

this.hash = original.hash;




Also in that case no additional space on the heap is allocated - it stays the same single final char array on the heap.



So you can assign a new String to a reference.(Give it an additional name). But it is allways the same unique String generated in your method and no new space on the heap is allocated.



So comparing the two methods in a first narrowing:



String europeanCountry = getEuropeanCountry();
String asianCountry = getAsianCountry();


and



String country = null;
country = getEuropeanCountry();
country = getAsianCountry();


Both will formaly create the same amount of Strings on the heap as the String is allways generated in the same methods. The variable are only references to that.



The only difference is that reusing in the second case allows formaly the String to be earlier garbage collected(In the moment the reference to it is removed by reusing the variable).



So with the second approach(reusing) you may generate a smaller memory footprint for a neclectable time.



I said in a first narrowing as this is only true if there is no other reference to the String and without optimization - so if no other reference exists and no optimization would take place the above would be the case.



However in your above code the variables don't exit scope and are never used. The compiler will detect this and no variable will be assigned at all. Depending on what the methods do they may be inlined and also not called. So what the methods you call look like makes a difference. Depending how complex they are the space on the heap is allocated or not.



Also the other way round: if you use the variable and runtime detects that you will likely call the method again for the same value, the value will be kept on the heap and not freed even if there is formal no reference and it could formally be garbage collected - so the assigment again makes no difference but the call of the method.



Also the obvioue: if the methods don't only generate the Strings but pull them from somewhere(a container) or store them somewhere that other reference is the one for which space on the heap is kept (and is) allocated and your assignment makes no difference at all regarding heap: it is the same final char array on the heap.



With that in mind the problem you are facing is most probably not that assignment of Strings but the design of your code. It must be a by far more complex scenario in which references are kept longer.



So far for your question.




For your problem i would look out:



  • for containers

  • where variables are generated

  • for frequent use . That is calling the methods very frequently for a lot of different values as in such case they are kept in memory for the next assumed call to happen.

  • for code where it is not easy to follow the flow of the data. The compiler optimizes by analyzing the flow. If you can't follow, it is more likely that the compiler can't neither than in other parts.






share|improve this answer
































    0














    Assuming lines of code shown are from single method(let me know if that's not the case), there are at least 3 issues I can point outwith the code:



    1. it seems method size is too large. Prefer writing methods that are as concise as possible and do just "one thing" and do it well.


    2. too much state change. In the 1st example where you set variable 'country' to 3 different method return values.


    3. consider using polymorphism, rather than repeating code in an if-else fashion for fetching the country


    finally, it's not clear how country values are used in methods.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071442%2fjava-creating-distinct-variables-vs-1-variable-for-multiple-values%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      For the question " I mean, in general, which way is better to use heap space and garbage collector efficiently?"



      Lets look at the String implementation e.g. jdk8 https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java



      public final class String

      implements java.io.Serializable, Comparable<String>, CharSequence {

      /** The value is used for character storage. */

      private final char value[];


      So it is a final character array - it cannot be reasigned or changed. So it is generated on the heap in your method and is never changed - only a reference(a name) is generated.



      To make no mistake lets also look at the constructor of a String (doing smth. like eg. "newString = new String(otherString)":



      public String(String original) 

      this.value = original.value;

      this.hash = original.hash;




      Also in that case no additional space on the heap is allocated - it stays the same single final char array on the heap.



      So you can assign a new String to a reference.(Give it an additional name). But it is allways the same unique String generated in your method and no new space on the heap is allocated.



      So comparing the two methods in a first narrowing:



      String europeanCountry = getEuropeanCountry();
      String asianCountry = getAsianCountry();


      and



      String country = null;
      country = getEuropeanCountry();
      country = getAsianCountry();


      Both will formaly create the same amount of Strings on the heap as the String is allways generated in the same methods. The variable are only references to that.



      The only difference is that reusing in the second case allows formaly the String to be earlier garbage collected(In the moment the reference to it is removed by reusing the variable).



      So with the second approach(reusing) you may generate a smaller memory footprint for a neclectable time.



      I said in a first narrowing as this is only true if there is no other reference to the String and without optimization - so if no other reference exists and no optimization would take place the above would be the case.



      However in your above code the variables don't exit scope and are never used. The compiler will detect this and no variable will be assigned at all. Depending on what the methods do they may be inlined and also not called. So what the methods you call look like makes a difference. Depending how complex they are the space on the heap is allocated or not.



      Also the other way round: if you use the variable and runtime detects that you will likely call the method again for the same value, the value will be kept on the heap and not freed even if there is formal no reference and it could formally be garbage collected - so the assigment again makes no difference but the call of the method.



      Also the obvioue: if the methods don't only generate the Strings but pull them from somewhere(a container) or store them somewhere that other reference is the one for which space on the heap is kept (and is) allocated and your assignment makes no difference at all regarding heap: it is the same final char array on the heap.



      With that in mind the problem you are facing is most probably not that assignment of Strings but the design of your code. It must be a by far more complex scenario in which references are kept longer.



      So far for your question.




      For your problem i would look out:



      • for containers

      • where variables are generated

      • for frequent use . That is calling the methods very frequently for a lot of different values as in such case they are kept in memory for the next assumed call to happen.

      • for code where it is not easy to follow the flow of the data. The compiler optimizes by analyzing the flow. If you can't follow, it is more likely that the compiler can't neither than in other parts.






      share|improve this answer





























        1














        For the question " I mean, in general, which way is better to use heap space and garbage collector efficiently?"



        Lets look at the String implementation e.g. jdk8 https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java



        public final class String

        implements java.io.Serializable, Comparable<String>, CharSequence {

        /** The value is used for character storage. */

        private final char value[];


        So it is a final character array - it cannot be reasigned or changed. So it is generated on the heap in your method and is never changed - only a reference(a name) is generated.



        To make no mistake lets also look at the constructor of a String (doing smth. like eg. "newString = new String(otherString)":



        public String(String original) 

        this.value = original.value;

        this.hash = original.hash;




        Also in that case no additional space on the heap is allocated - it stays the same single final char array on the heap.



        So you can assign a new String to a reference.(Give it an additional name). But it is allways the same unique String generated in your method and no new space on the heap is allocated.



        So comparing the two methods in a first narrowing:



        String europeanCountry = getEuropeanCountry();
        String asianCountry = getAsianCountry();


        and



        String country = null;
        country = getEuropeanCountry();
        country = getAsianCountry();


        Both will formaly create the same amount of Strings on the heap as the String is allways generated in the same methods. The variable are only references to that.



        The only difference is that reusing in the second case allows formaly the String to be earlier garbage collected(In the moment the reference to it is removed by reusing the variable).



        So with the second approach(reusing) you may generate a smaller memory footprint for a neclectable time.



        I said in a first narrowing as this is only true if there is no other reference to the String and without optimization - so if no other reference exists and no optimization would take place the above would be the case.



        However in your above code the variables don't exit scope and are never used. The compiler will detect this and no variable will be assigned at all. Depending on what the methods do they may be inlined and also not called. So what the methods you call look like makes a difference. Depending how complex they are the space on the heap is allocated or not.



        Also the other way round: if you use the variable and runtime detects that you will likely call the method again for the same value, the value will be kept on the heap and not freed even if there is formal no reference and it could formally be garbage collected - so the assigment again makes no difference but the call of the method.



        Also the obvioue: if the methods don't only generate the Strings but pull them from somewhere(a container) or store them somewhere that other reference is the one for which space on the heap is kept (and is) allocated and your assignment makes no difference at all regarding heap: it is the same final char array on the heap.



        With that in mind the problem you are facing is most probably not that assignment of Strings but the design of your code. It must be a by far more complex scenario in which references are kept longer.



        So far for your question.




        For your problem i would look out:



        • for containers

        • where variables are generated

        • for frequent use . That is calling the methods very frequently for a lot of different values as in such case they are kept in memory for the next assumed call to happen.

        • for code where it is not easy to follow the flow of the data. The compiler optimizes by analyzing the flow. If you can't follow, it is more likely that the compiler can't neither than in other parts.






        share|improve this answer



























          1












          1








          1







          For the question " I mean, in general, which way is better to use heap space and garbage collector efficiently?"



          Lets look at the String implementation e.g. jdk8 https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java



          public final class String

          implements java.io.Serializable, Comparable<String>, CharSequence {

          /** The value is used for character storage. */

          private final char value[];


          So it is a final character array - it cannot be reasigned or changed. So it is generated on the heap in your method and is never changed - only a reference(a name) is generated.



          To make no mistake lets also look at the constructor of a String (doing smth. like eg. "newString = new String(otherString)":



          public String(String original) 

          this.value = original.value;

          this.hash = original.hash;




          Also in that case no additional space on the heap is allocated - it stays the same single final char array on the heap.



          So you can assign a new String to a reference.(Give it an additional name). But it is allways the same unique String generated in your method and no new space on the heap is allocated.



          So comparing the two methods in a first narrowing:



          String europeanCountry = getEuropeanCountry();
          String asianCountry = getAsianCountry();


          and



          String country = null;
          country = getEuropeanCountry();
          country = getAsianCountry();


          Both will formaly create the same amount of Strings on the heap as the String is allways generated in the same methods. The variable are only references to that.



          The only difference is that reusing in the second case allows formaly the String to be earlier garbage collected(In the moment the reference to it is removed by reusing the variable).



          So with the second approach(reusing) you may generate a smaller memory footprint for a neclectable time.



          I said in a first narrowing as this is only true if there is no other reference to the String and without optimization - so if no other reference exists and no optimization would take place the above would be the case.



          However in your above code the variables don't exit scope and are never used. The compiler will detect this and no variable will be assigned at all. Depending on what the methods do they may be inlined and also not called. So what the methods you call look like makes a difference. Depending how complex they are the space on the heap is allocated or not.



          Also the other way round: if you use the variable and runtime detects that you will likely call the method again for the same value, the value will be kept on the heap and not freed even if there is formal no reference and it could formally be garbage collected - so the assigment again makes no difference but the call of the method.



          Also the obvioue: if the methods don't only generate the Strings but pull them from somewhere(a container) or store them somewhere that other reference is the one for which space on the heap is kept (and is) allocated and your assignment makes no difference at all regarding heap: it is the same final char array on the heap.



          With that in mind the problem you are facing is most probably not that assignment of Strings but the design of your code. It must be a by far more complex scenario in which references are kept longer.



          So far for your question.




          For your problem i would look out:



          • for containers

          • where variables are generated

          • for frequent use . That is calling the methods very frequently for a lot of different values as in such case they are kept in memory for the next assumed call to happen.

          • for code where it is not easy to follow the flow of the data. The compiler optimizes by analyzing the flow. If you can't follow, it is more likely that the compiler can't neither than in other parts.






          share|improve this answer















          For the question " I mean, in general, which way is better to use heap space and garbage collector efficiently?"



          Lets look at the String implementation e.g. jdk8 https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java



          public final class String

          implements java.io.Serializable, Comparable<String>, CharSequence {

          /** The value is used for character storage. */

          private final char value[];


          So it is a final character array - it cannot be reasigned or changed. So it is generated on the heap in your method and is never changed - only a reference(a name) is generated.



          To make no mistake lets also look at the constructor of a String (doing smth. like eg. "newString = new String(otherString)":



          public String(String original) 

          this.value = original.value;

          this.hash = original.hash;




          Also in that case no additional space on the heap is allocated - it stays the same single final char array on the heap.



          So you can assign a new String to a reference.(Give it an additional name). But it is allways the same unique String generated in your method and no new space on the heap is allocated.



          So comparing the two methods in a first narrowing:



          String europeanCountry = getEuropeanCountry();
          String asianCountry = getAsianCountry();


          and



          String country = null;
          country = getEuropeanCountry();
          country = getAsianCountry();


          Both will formaly create the same amount of Strings on the heap as the String is allways generated in the same methods. The variable are only references to that.



          The only difference is that reusing in the second case allows formaly the String to be earlier garbage collected(In the moment the reference to it is removed by reusing the variable).



          So with the second approach(reusing) you may generate a smaller memory footprint for a neclectable time.



          I said in a first narrowing as this is only true if there is no other reference to the String and without optimization - so if no other reference exists and no optimization would take place the above would be the case.



          However in your above code the variables don't exit scope and are never used. The compiler will detect this and no variable will be assigned at all. Depending on what the methods do they may be inlined and also not called. So what the methods you call look like makes a difference. Depending how complex they are the space on the heap is allocated or not.



          Also the other way round: if you use the variable and runtime detects that you will likely call the method again for the same value, the value will be kept on the heap and not freed even if there is formal no reference and it could formally be garbage collected - so the assigment again makes no difference but the call of the method.



          Also the obvioue: if the methods don't only generate the Strings but pull them from somewhere(a container) or store them somewhere that other reference is the one for which space on the heap is kept (and is) allocated and your assignment makes no difference at all regarding heap: it is the same final char array on the heap.



          With that in mind the problem you are facing is most probably not that assignment of Strings but the design of your code. It must be a by far more complex scenario in which references are kept longer.



          So far for your question.




          For your problem i would look out:



          • for containers

          • where variables are generated

          • for frequent use . That is calling the methods very frequently for a lot of different values as in such case they are kept in memory for the next assumed call to happen.

          • for code where it is not easy to follow the flow of the data. The compiler optimizes by analyzing the flow. If you can't follow, it is more likely that the compiler can't neither than in other parts.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 9 at 0:15

























          answered Mar 8 at 22:33









          kaikai

          7361310




          7361310























              0














              Assuming lines of code shown are from single method(let me know if that's not the case), there are at least 3 issues I can point outwith the code:



              1. it seems method size is too large. Prefer writing methods that are as concise as possible and do just "one thing" and do it well.


              2. too much state change. In the 1st example where you set variable 'country' to 3 different method return values.


              3. consider using polymorphism, rather than repeating code in an if-else fashion for fetching the country


              finally, it's not clear how country values are used in methods.






              share|improve this answer



























                0














                Assuming lines of code shown are from single method(let me know if that's not the case), there are at least 3 issues I can point outwith the code:



                1. it seems method size is too large. Prefer writing methods that are as concise as possible and do just "one thing" and do it well.


                2. too much state change. In the 1st example where you set variable 'country' to 3 different method return values.


                3. consider using polymorphism, rather than repeating code in an if-else fashion for fetching the country


                finally, it's not clear how country values are used in methods.






                share|improve this answer

























                  0












                  0








                  0







                  Assuming lines of code shown are from single method(let me know if that's not the case), there are at least 3 issues I can point outwith the code:



                  1. it seems method size is too large. Prefer writing methods that are as concise as possible and do just "one thing" and do it well.


                  2. too much state change. In the 1st example where you set variable 'country' to 3 different method return values.


                  3. consider using polymorphism, rather than repeating code in an if-else fashion for fetching the country


                  finally, it's not clear how country values are used in methods.






                  share|improve this answer













                  Assuming lines of code shown are from single method(let me know if that's not the case), there are at least 3 issues I can point outwith the code:



                  1. it seems method size is too large. Prefer writing methods that are as concise as possible and do just "one thing" and do it well.


                  2. too much state change. In the 1st example where you set variable 'country' to 3 different method return values.


                  3. consider using polymorphism, rather than repeating code in an if-else fashion for fetching the country


                  finally, it's not clear how country values are used in methods.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 22:30









                  Maaddhu MikkiliMaaddhu Mikkili

                  1




                  1



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071442%2fjava-creating-distinct-variables-vs-1-variable-for-multiple-values%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

                      Алба-Юлія

                      Захаров Федір Захарович