Why is the number of local variables used in a Java bytecode method not the most economical?How to round a number to n decimal places in JavaWhy can't static methods be abstract in JavaWhy does Java have transient fields?Local variables in java bytecodeJava: when to use static methodsBytecode features not available in the Java languageWhy are there local variables in stack-based IL bytecodeWhy is executing Java code in comments with certain Unicode characters allowed?Why does array[idx++]+=“a” increase idx once in Java 8 but twice in Java 9 and 10?Why is 2 * (i * i) faster than 2 * i * i in Java?

Converting 8V AC to 8V DC - bridge rectifier gets very hot while idling

Old French song lyrics with the word "baiser."

Suggestions for protecting jeans from saddle clamp bolt

Finding minimum time for vehicle to reach to its destination

Melee or Ranged attacks by Monsters, no distinction in modifiers?

Why does Canada require mandatory bilingualism in all government posts?

The best place for swimming in Arctic Ocean

If Trump gets impeached, how long would Pence be president?

How to apply the changes to my `.zshrc` file after edit?

When does Haskell complain about incorrect typing in functions?

Why is it considered Acid Rain with pH <5.6

Can anyone give a concrete example to illustrate what is an uniform prior?

Is a fighting a fallen friend with the help of a redeemed villain story too much for one book

Use cases for M-0 & C-0?

Pointwise convergence of uniformly continuous functions to zero, but not uniformly

Assuring luggage isn't lost with short layover

Why didn't Britain or any other European power colonise Abyssinia/Ethiopia before 1936?

How can religions be structured in ways that allow inter-faith councils to work?

To find islands of 1 and 0 in matrix

Send a single HTML email from Thunderbird, overriding the default "plain text" setting

Polyhedra, Polyhedron, Polytopes and Polygon

How to store my pliers and wire cutters on my desk?

How much were the LMs maneuvered to their landing points?

Checking if an integer is a member of an integer list



Why is the number of local variables used in a Java bytecode method not the most economical?


How to round a number to n decimal places in JavaWhy can't static methods be abstract in JavaWhy does Java have transient fields?Local variables in java bytecodeJava: when to use static methodsBytecode features not available in the Java languageWhy are there local variables in stack-based IL bytecodeWhy is executing Java code in comments with certain Unicode characters allowed?Why does array[idx++]+=“a” increase idx once in Java 8 but twice in Java 9 and 10?Why is 2 * (i * i) faster than 2 * i * i in Java?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















I have a snippet of simple Java code:



public static void main(Strings[] args) 
String testStr = "test";
String rst = testStr + 1 + "a" + "pig" + 2;
System.out.println(rst);



Compile it with the Eclipse Java compiler, and examine the bytecode using AsmTools. It shows:



byte code



There are three local variables in the method. The argument is in slot 0, and slots 1 and 2 are supposedly used by the code. But I think 2 local variables are just enough — index 0 is the argument anyway, and the code needs only one more variable.



In order to see if my idea is correct, I edited the textual bytecode, reduced the number of local variables to 2, and adjusted some related instructions:



edited



I recompiled it with AsmTools and it works fine!



So why don't Javac or the Eclipse compiler do this kind of optimization to use the minimal local variables?










share|improve this question






























    6















    I have a snippet of simple Java code:



    public static void main(Strings[] args) 
    String testStr = "test";
    String rst = testStr + 1 + "a" + "pig" + 2;
    System.out.println(rst);



    Compile it with the Eclipse Java compiler, and examine the bytecode using AsmTools. It shows:



    byte code



    There are three local variables in the method. The argument is in slot 0, and slots 1 and 2 are supposedly used by the code. But I think 2 local variables are just enough — index 0 is the argument anyway, and the code needs only one more variable.



    In order to see if my idea is correct, I edited the textual bytecode, reduced the number of local variables to 2, and adjusted some related instructions:



    edited



    I recompiled it with AsmTools and it works fine!



    So why don't Javac or the Eclipse compiler do this kind of optimization to use the minimal local variables?










    share|improve this question


























      6












      6








      6


      4






      I have a snippet of simple Java code:



      public static void main(Strings[] args) 
      String testStr = "test";
      String rst = testStr + 1 + "a" + "pig" + 2;
      System.out.println(rst);



      Compile it with the Eclipse Java compiler, and examine the bytecode using AsmTools. It shows:



      byte code



      There are three local variables in the method. The argument is in slot 0, and slots 1 and 2 are supposedly used by the code. But I think 2 local variables are just enough — index 0 is the argument anyway, and the code needs only one more variable.



      In order to see if my idea is correct, I edited the textual bytecode, reduced the number of local variables to 2, and adjusted some related instructions:



      edited



      I recompiled it with AsmTools and it works fine!



      So why don't Javac or the Eclipse compiler do this kind of optimization to use the minimal local variables?










      share|improve this question
















      I have a snippet of simple Java code:



      public static void main(Strings[] args) 
      String testStr = "test";
      String rst = testStr + 1 + "a" + "pig" + 2;
      System.out.println(rst);



      Compile it with the Eclipse Java compiler, and examine the bytecode using AsmTools. It shows:



      byte code



      There are three local variables in the method. The argument is in slot 0, and slots 1 and 2 are supposedly used by the code. But I think 2 local variables are just enough — index 0 is the argument anyway, and the code needs only one more variable.



      In order to see if my idea is correct, I edited the textual bytecode, reduced the number of local variables to 2, and adjusted some related instructions:



      edited



      I recompiled it with AsmTools and it works fine!



      So why don't Javac or the Eclipse compiler do this kind of optimization to use the minimal local variables?







      java jvm javac bytecode






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 7 hours ago









      Boann

      38.5k13 gold badges93 silver badges123 bronze badges




      38.5k13 gold badges93 silver badges123 bronze badges










      asked 8 hours ago









      pf_milespf_miles

      3683 silver badges13 bronze badges




      3683 silver badges13 bronze badges






















          3 Answers
          3






          active

          oldest

          votes


















          7














          There are several reasons. First off, it's not necessary for performance. The JVM already optimizes things at runtime, so there's no point in adding redundant complexity to the compiler.



          However, another major reason noone has mentioned here is debugging. Making the bytecode as close to the original source as possible makes it a lot easier to debug.






          share|improve this answer


















          • 3





            Good point about debugging!

            – GhostCat
            8 hours ago











          • Yes. Byte code is not an executable code. It will be interpreted before execution. The executable code much be much different.

            – mentallurg
            7 hours ago


















          5














          One LOCALVARIABLE for args, one for testStr and one for rst:



          LOCALVARIABLE args [Ljava/lang/String;
          LOCALVARIABLE testStr Ljava/lang/String;
          LOCALVARIABLE rst Ljava/lang/String;
          MAXSTACK = 2
          MAXLOCALS = 3


          P.S. Compilers are not so smart as people. This example is easy, but more complicated variant could lead to significant performance overhead during the compilation phase.






          share|improve this answer
































            4














            Simply because Java gains performance from the just in time compiler.



            What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime.



            Meaning: the jvm decides at runtime if a method is worth translating into (highly optimized!) machine code. If the jvm decides "not worth optimising", why make javac more complex and slower by having a lot of optimization in there? Plus: the more simple and basic the incoming byte code, the easier it is for the JIT to analyze and improve that input!






            share|improve this answer























            • "What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime." - This is true to an extent, especially in OPs case. However, some JIT features do depend on how the code is written, such as escape analysis, which helps determines eligibility for other optimizations (such as scalar replacement). Source code matters even when it hits javac (auto boxing pitfalls, string builder pitfalls, etc..). I wouldn't recommend people rely too much on JIT to clean their code, rather they should avoid pre-optimizing as OP is doing, focus on real problems.

              – Vince Emigh
              5 hours ago












            • @VinceEmigh Sure. The JIT isn't about fixing stupid mistakes on the programmers side. I see it the other way round: you avoid the stupid mistakes, you write, clean, simple code, and then you let the heavy lifting happen at runtime. And if things aren't performing as expected or required, you carefully measure what is going on.

              – GhostCat
              4 hours ago













            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%2f57242587%2fwhy-is-the-number-of-local-variables-used-in-a-java-bytecode-method-not-the-most%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            7














            There are several reasons. First off, it's not necessary for performance. The JVM already optimizes things at runtime, so there's no point in adding redundant complexity to the compiler.



            However, another major reason noone has mentioned here is debugging. Making the bytecode as close to the original source as possible makes it a lot easier to debug.






            share|improve this answer


















            • 3





              Good point about debugging!

              – GhostCat
              8 hours ago











            • Yes. Byte code is not an executable code. It will be interpreted before execution. The executable code much be much different.

              – mentallurg
              7 hours ago















            7














            There are several reasons. First off, it's not necessary for performance. The JVM already optimizes things at runtime, so there's no point in adding redundant complexity to the compiler.



            However, another major reason noone has mentioned here is debugging. Making the bytecode as close to the original source as possible makes it a lot easier to debug.






            share|improve this answer


















            • 3





              Good point about debugging!

              – GhostCat
              8 hours ago











            • Yes. Byte code is not an executable code. It will be interpreted before execution. The executable code much be much different.

              – mentallurg
              7 hours ago













            7












            7








            7







            There are several reasons. First off, it's not necessary for performance. The JVM already optimizes things at runtime, so there's no point in adding redundant complexity to the compiler.



            However, another major reason noone has mentioned here is debugging. Making the bytecode as close to the original source as possible makes it a lot easier to debug.






            share|improve this answer













            There are several reasons. First off, it's not necessary for performance. The JVM already optimizes things at runtime, so there's no point in adding redundant complexity to the compiler.



            However, another major reason noone has mentioned here is debugging. Making the bytecode as close to the original source as possible makes it a lot easier to debug.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 8 hours ago









            AntimonyAntimony

            28.3k6 gold badges73 silver badges82 bronze badges




            28.3k6 gold badges73 silver badges82 bronze badges







            • 3





              Good point about debugging!

              – GhostCat
              8 hours ago











            • Yes. Byte code is not an executable code. It will be interpreted before execution. The executable code much be much different.

              – mentallurg
              7 hours ago












            • 3





              Good point about debugging!

              – GhostCat
              8 hours ago











            • Yes. Byte code is not an executable code. It will be interpreted before execution. The executable code much be much different.

              – mentallurg
              7 hours ago







            3




            3





            Good point about debugging!

            – GhostCat
            8 hours ago





            Good point about debugging!

            – GhostCat
            8 hours ago













            Yes. Byte code is not an executable code. It will be interpreted before execution. The executable code much be much different.

            – mentallurg
            7 hours ago





            Yes. Byte code is not an executable code. It will be interpreted before execution. The executable code much be much different.

            – mentallurg
            7 hours ago













            5














            One LOCALVARIABLE for args, one for testStr and one for rst:



            LOCALVARIABLE args [Ljava/lang/String;
            LOCALVARIABLE testStr Ljava/lang/String;
            LOCALVARIABLE rst Ljava/lang/String;
            MAXSTACK = 2
            MAXLOCALS = 3


            P.S. Compilers are not so smart as people. This example is easy, but more complicated variant could lead to significant performance overhead during the compilation phase.






            share|improve this answer





























              5














              One LOCALVARIABLE for args, one for testStr and one for rst:



              LOCALVARIABLE args [Ljava/lang/String;
              LOCALVARIABLE testStr Ljava/lang/String;
              LOCALVARIABLE rst Ljava/lang/String;
              MAXSTACK = 2
              MAXLOCALS = 3


              P.S. Compilers are not so smart as people. This example is easy, but more complicated variant could lead to significant performance overhead during the compilation phase.






              share|improve this answer



























                5












                5








                5







                One LOCALVARIABLE for args, one for testStr and one for rst:



                LOCALVARIABLE args [Ljava/lang/String;
                LOCALVARIABLE testStr Ljava/lang/String;
                LOCALVARIABLE rst Ljava/lang/String;
                MAXSTACK = 2
                MAXLOCALS = 3


                P.S. Compilers are not so smart as people. This example is easy, but more complicated variant could lead to significant performance overhead during the compilation phase.






                share|improve this answer















                One LOCALVARIABLE for args, one for testStr and one for rst:



                LOCALVARIABLE args [Ljava/lang/String;
                LOCALVARIABLE testStr Ljava/lang/String;
                LOCALVARIABLE rst Ljava/lang/String;
                MAXSTACK = 2
                MAXLOCALS = 3


                P.S. Compilers are not so smart as people. This example is easy, but more complicated variant could lead to significant performance overhead during the compilation phase.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 8 hours ago

























                answered 8 hours ago









                Oleksandr PyrohovOleksandr Pyrohov

                10.8k4 gold badges44 silver badges76 bronze badges




                10.8k4 gold badges44 silver badges76 bronze badges





















                    4














                    Simply because Java gains performance from the just in time compiler.



                    What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime.



                    Meaning: the jvm decides at runtime if a method is worth translating into (highly optimized!) machine code. If the jvm decides "not worth optimising", why make javac more complex and slower by having a lot of optimization in there? Plus: the more simple and basic the incoming byte code, the easier it is for the JIT to analyze and improve that input!






                    share|improve this answer























                    • "What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime." - This is true to an extent, especially in OPs case. However, some JIT features do depend on how the code is written, such as escape analysis, which helps determines eligibility for other optimizations (such as scalar replacement). Source code matters even when it hits javac (auto boxing pitfalls, string builder pitfalls, etc..). I wouldn't recommend people rely too much on JIT to clean their code, rather they should avoid pre-optimizing as OP is doing, focus on real problems.

                      – Vince Emigh
                      5 hours ago












                    • @VinceEmigh Sure. The JIT isn't about fixing stupid mistakes on the programmers side. I see it the other way round: you avoid the stupid mistakes, you write, clean, simple code, and then you let the heavy lifting happen at runtime. And if things aren't performing as expected or required, you carefully measure what is going on.

                      – GhostCat
                      4 hours ago















                    4














                    Simply because Java gains performance from the just in time compiler.



                    What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime.



                    Meaning: the jvm decides at runtime if a method is worth translating into (highly optimized!) machine code. If the jvm decides "not worth optimising", why make javac more complex and slower by having a lot of optimization in there? Plus: the more simple and basic the incoming byte code, the easier it is for the JIT to analyze and improve that input!






                    share|improve this answer























                    • "What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime." - This is true to an extent, especially in OPs case. However, some JIT features do depend on how the code is written, such as escape analysis, which helps determines eligibility for other optimizations (such as scalar replacement). Source code matters even when it hits javac (auto boxing pitfalls, string builder pitfalls, etc..). I wouldn't recommend people rely too much on JIT to clean their code, rather they should avoid pre-optimizing as OP is doing, focus on real problems.

                      – Vince Emigh
                      5 hours ago












                    • @VinceEmigh Sure. The JIT isn't about fixing stupid mistakes on the programmers side. I see it the other way round: you avoid the stupid mistakes, you write, clean, simple code, and then you let the heavy lifting happen at runtime. And if things aren't performing as expected or required, you carefully measure what is going on.

                      – GhostCat
                      4 hours ago













                    4












                    4








                    4







                    Simply because Java gains performance from the just in time compiler.



                    What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime.



                    Meaning: the jvm decides at runtime if a method is worth translating into (highly optimized!) machine code. If the jvm decides "not worth optimising", why make javac more complex and slower by having a lot of optimization in there? Plus: the more simple and basic the incoming byte code, the easier it is for the JIT to analyze and improve that input!






                    share|improve this answer













                    Simply because Java gains performance from the just in time compiler.



                    What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime.



                    Meaning: the jvm decides at runtime if a method is worth translating into (highly optimized!) machine code. If the jvm decides "not worth optimising", why make javac more complex and slower by having a lot of optimization in there? Plus: the more simple and basic the incoming byte code, the easier it is for the JIT to analyze and improve that input!







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 8 hours ago









                    GhostCatGhostCat

                    107k17 gold badges104 silver badges179 bronze badges




                    107k17 gold badges104 silver badges179 bronze badges












                    • "What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime." - This is true to an extent, especially in OPs case. However, some JIT features do depend on how the code is written, such as escape analysis, which helps determines eligibility for other optimizations (such as scalar replacement). Source code matters even when it hits javac (auto boxing pitfalls, string builder pitfalls, etc..). I wouldn't recommend people rely too much on JIT to clean their code, rather they should avoid pre-optimizing as OP is doing, focus on real problems.

                      – Vince Emigh
                      5 hours ago












                    • @VinceEmigh Sure. The JIT isn't about fixing stupid mistakes on the programmers side. I see it the other way round: you avoid the stupid mistakes, you write, clean, simple code, and then you let the heavy lifting happen at runtime. And if things aren't performing as expected or required, you carefully measure what is going on.

                      – GhostCat
                      4 hours ago

















                    • "What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime." - This is true to an extent, especially in OPs case. However, some JIT features do depend on how the code is written, such as escape analysis, which helps determines eligibility for other optimizations (such as scalar replacement). Source code matters even when it hits javac (auto boxing pitfalls, string builder pitfalls, etc..). I wouldn't recommend people rely too much on JIT to clean their code, rather they should avoid pre-optimizing as OP is doing, focus on real problems.

                      – Vince Emigh
                      5 hours ago












                    • @VinceEmigh Sure. The JIT isn't about fixing stupid mistakes on the programmers side. I see it the other way round: you avoid the stupid mistakes, you write, clean, simple code, and then you let the heavy lifting happen at runtime. And if things aren't performing as expected or required, you carefully measure what is going on.

                      – GhostCat
                      4 hours ago
















                    "What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime." - This is true to an extent, especially in OPs case. However, some JIT features do depend on how the code is written, such as escape analysis, which helps determines eligibility for other optimizations (such as scalar replacement). Source code matters even when it hits javac (auto boxing pitfalls, string builder pitfalls, etc..). I wouldn't recommend people rely too much on JIT to clean their code, rather they should avoid pre-optimizing as OP is doing, focus on real problems.

                    – Vince Emigh
                    5 hours ago






                    "What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime." - This is true to an extent, especially in OPs case. However, some JIT features do depend on how the code is written, such as escape analysis, which helps determines eligibility for other optimizations (such as scalar replacement). Source code matters even when it hits javac (auto boxing pitfalls, string builder pitfalls, etc..). I wouldn't recommend people rely too much on JIT to clean their code, rather they should avoid pre-optimizing as OP is doing, focus on real problems.

                    – Vince Emigh
                    5 hours ago














                    @VinceEmigh Sure. The JIT isn't about fixing stupid mistakes on the programmers side. I see it the other way round: you avoid the stupid mistakes, you write, clean, simple code, and then you let the heavy lifting happen at runtime. And if things aren't performing as expected or required, you carefully measure what is going on.

                    – GhostCat
                    4 hours ago





                    @VinceEmigh Sure. The JIT isn't about fixing stupid mistakes on the programmers side. I see it the other way round: you avoid the stupid mistakes, you write, clean, simple code, and then you let the heavy lifting happen at runtime. And if things aren't performing as expected or required, you carefully measure what is going on.

                    – GhostCat
                    4 hours ago

















                    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%2f57242587%2fwhy-is-the-number-of-local-variables-used-in-a-java-bytecode-method-not-the-most%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

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單