Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Cosmetic vs More Efficient

Cosmetic vs More Efficient

Scheduled Pinned Locked Moved The Lounge
visual-studiocomalgorithmsquestion
48 Posts 27 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • W W Balboos GHB

    The difference may be slight but one of the conundrums I find myself in is using a ternary operator to handle a default vs non-default assignment. Simplified:

    function whatEver(inVal=NULL) { // here, NULL is a default value for a function argument

    // This ?
    if(inVal==NULL)
    inVal = internalDefault;

    // or this?
    inVal = (inVal==NULL)?internalDefault:inVal;

    } // function whatEver(inVal=NULL)

    The first should be a touch more efficient as it only does an assignment when necessary, but generally an insignificant difference. So - what would you do, and, do you ever pause and consider it before choosing?

    Ravings en masse^

    "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

    "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

    A Offline
    A Offline
    Al Gonzalez
    wrote on last edited by
    #36

    I don't think it matters much as the compilers are pretty efficient at this. In C#, I usually use the "null coalescing assignment operator (??=)"; so "inVal ??= internalVal;". Here are some functions to test the various ways to assign a default value:

    void FixNullArg_SimpleIf(string arg = null) {
    if (arg == null)
    arg = "Fix null via simple if";
    Console.WriteLine(arg);
    }
    void FixNullArg_TernaryOp(string arg = null)
    {
    arg = (arg == null) ? "Fix null via ternary operator" : arg;
    Console.WriteLine(arg);
    }
    void FixNullArg_NullCoalescingOp(string arg = null)
    {
    arg = arg ?? "Fix null via ?? operator";
    Console.WriteLine(arg);
    }
    void FixNullArg_NullCoalescingAssignmentOp(string arg = null)
    {
    arg ??= "Fix null via ??= operator";
    Console.WriteLine(arg);
    }
    void FixNullArg_IsNullOrWhiteSpace(string arg = null)
    {
    arg = string.IsNullOrWhiteSpace(arg) ? "Fix null via IsNullOrWhiteSpace" : arg;
    Console.WriteLine(arg);
    }

    And here is the decompiled Intermediate Language (IL):

    FixNullArg_SimpleIf:
    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: ldnull
    IL_0003: ceq
    IL_0005: stloc.0
    IL_0006: ldloc.0
    IL_0007: brfalse.s IL_0010
    IL_0009: ldstr "Fix null via simple if"
    IL_000E: starg.s 01
    IL_0010: ldarg.1
    IL_0011: call System.Console.WriteLine
    IL_0016: nop
    IL_0017: ret

    FixNullArg_TernaryOp:
    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: brfalse.s IL_0007
    IL_0004: ldarg.1
    IL_0005: br.s IL_000C
    IL_0007: ldstr "Fix null via ternary operator"
    IL_000C: starg.s 01
    IL_000E: ldarg.1
    IL_000F: call System.Console.WriteLine
    IL_0014: nop
    IL_0015: ret

    FixNullArg_NullCoalescingOp:
    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: dup
    IL_0003: brtrue.s IL_000B
    IL_0005: pop
    IL_0006: ldstr "Fix null via ?? operator"
    IL_000B: starg.s 01
    IL_000D: ldarg.1
    IL_000E: call System.Console.WriteLine
    IL_0013: nop
    IL_0014: ret

    FixNullArg_NullCoalescingAssignmentOp:
    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: brtrue.s IL_000B
    IL_0004: ldstr "Fix null via ??= operator"
    IL_0009: starg.s 01
    IL_000B: ldarg.1
    IL_000C: call System.Console.WriteLine
    IL_0011: nop
    IL_0012: ret

    FixNullArg_IsNullOrWhiteSpace:
    IL_0

    1 Reply Last reply
    0
    • W W Balboos GHB

      The difference may be slight but one of the conundrums I find myself in is using a ternary operator to handle a default vs non-default assignment. Simplified:

      function whatEver(inVal=NULL) { // here, NULL is a default value for a function argument

      // This ?
      if(inVal==NULL)
      inVal = internalDefault;

      // or this?
      inVal = (inVal==NULL)?internalDefault:inVal;

      } // function whatEver(inVal=NULL)

      The first should be a touch more efficient as it only does an assignment when necessary, but generally an insignificant difference. So - what would you do, and, do you ever pause and consider it before choosing?

      Ravings en masse^

      "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

      "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

      S Offline
      S Offline
      SeattleC
      wrote on last edited by
      #37

      You should not write off the compiler so soon. A C++ compiler probably generates the same code for either statement. So you can have cosmetic and efficient.

      1 Reply Last reply
      0
      • W W Balboos GHB

        The difference may be slight but one of the conundrums I find myself in is using a ternary operator to handle a default vs non-default assignment. Simplified:

        function whatEver(inVal=NULL) { // here, NULL is a default value for a function argument

        // This ?
        if(inVal==NULL)
        inVal = internalDefault;

        // or this?
        inVal = (inVal==NULL)?internalDefault:inVal;

        } // function whatEver(inVal=NULL)

        The first should be a touch more efficient as it only does an assignment when necessary, but generally an insignificant difference. So - what would you do, and, do you ever pause and consider it before choosing?

        Ravings en masse^

        "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

        "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

        J Offline
        J Offline
        JP Reyes
        wrote on last edited by
        #38

        In ASM/C/C++, efficiency and performance always outweigh readability. If a Padawan cannot read it, he is not ready to become a Jedi.

        1 Reply Last reply
        0
        • W W Balboos GHB

          The difference may be slight but one of the conundrums I find myself in is using a ternary operator to handle a default vs non-default assignment. Simplified:

          function whatEver(inVal=NULL) { // here, NULL is a default value for a function argument

          // This ?
          if(inVal==NULL)
          inVal = internalDefault;

          // or this?
          inVal = (inVal==NULL)?internalDefault:inVal;

          } // function whatEver(inVal=NULL)

          The first should be a touch more efficient as it only does an assignment when necessary, but generally an insignificant difference. So - what would you do, and, do you ever pause and consider it before choosing?

          Ravings en masse^

          "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

          "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

          Z Offline
          Z Offline
          Zuoliu Ding
          wrote on last edited by
          #39

          This looks like a script function not in C/C++. As for this example in VC++ void whatEver(int inVal) { // This ? if(inVal==0) inVal = internalDefault; // or this? inVal = (inVal==0)?internalDefault:inVal; } // function whatEver(inVal=NULL) See disassembly code in Debug build as simply: ; 16 : // This ? ; 17 : if(inVal==0) cmp DWORD PTR _inVal$[ebp], 0 jne SHORT $LN2@whatEver ; 18 : inVal = internalDefault; mov DWORD PTR _inVal$[ebp], 123 ; 0000007bH $LN2@whatEver: While the other just ; 21 : inVal = (inVal==0)?internalDefault:inVal; cmp DWORD PTR _inVal$[ebp], 0 jne SHORT $LN4@whatEver mov DWORD PTR tv66[ebp], 123 ; 0000007bH jmp SHORT $LN5@whatEver $LN4@whatEver: mov eax, DWORD PTR _inVal$[ebp] mov DWORD PTR tv66[ebp], eax $LN5@whatEver: mov ecx, DWORD PTR tv66[ebp] mov DWORD PTR _inVal$[ebp], ecx But you can't see both in Release build because both optimized in compilation.

          W 1 Reply Last reply
          0
          • Z Zuoliu Ding

            This looks like a script function not in C/C++. As for this example in VC++ void whatEver(int inVal) { // This ? if(inVal==0) inVal = internalDefault; // or this? inVal = (inVal==0)?internalDefault:inVal; } // function whatEver(inVal=NULL) See disassembly code in Debug build as simply: ; 16 : // This ? ; 17 : if(inVal==0) cmp DWORD PTR _inVal$[ebp], 0 jne SHORT $LN2@whatEver ; 18 : inVal = internalDefault; mov DWORD PTR _inVal$[ebp], 123 ; 0000007bH $LN2@whatEver: While the other just ; 21 : inVal = (inVal==0)?internalDefault:inVal; cmp DWORD PTR _inVal$[ebp], 0 jne SHORT $LN4@whatEver mov DWORD PTR tv66[ebp], 123 ; 0000007bH jmp SHORT $LN5@whatEver $LN4@whatEver: mov eax, DWORD PTR _inVal$[ebp] mov DWORD PTR tv66[ebp], eax $LN5@whatEver: mov ecx, DWORD PTR tv66[ebp] mov DWORD PTR _inVal$[ebp], ecx But you can't see both in Release build because both optimized in compilation.

            W Offline
            W Offline
            W Balboos GHB
            wrote on last edited by
            #40

            You are overthinking this. First - it is script-like. The C++ was just a posting choice for formatting - apparently a poor choice on my part as many others also though I meant in the C++ context. Second - this was really a question on preferences. Aside from your disassembly, the clear difference is one would (as written) always MOVe a value and the other only conditionally - both doing the same conditional test. The question is, for most applications, which would you rather see - in your own code and someone else's your stuck looking at. The script style of the function, very PHP-like, was to illustrate the function declaration and content all in one small location. In a PHP script roughly like this it acts in a similar manner to a C++ function overload (one with an arg, one without). On the other hand, I appreciate your thoughts and dis-assembly. I've not disassembled code ( once upon a time I had a x86 commenting disassembler) in a very many years.

            Ravings en masse^

            "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

            "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

            Z 1 Reply Last reply
            0
            • W W Balboos GHB

              You are overthinking this. First - it is script-like. The C++ was just a posting choice for formatting - apparently a poor choice on my part as many others also though I meant in the C++ context. Second - this was really a question on preferences. Aside from your disassembly, the clear difference is one would (as written) always MOVe a value and the other only conditionally - both doing the same conditional test. The question is, for most applications, which would you rather see - in your own code and someone else's your stuck looking at. The script style of the function, very PHP-like, was to illustrate the function declaration and content all in one small location. In a PHP script roughly like this it acts in a similar manner to a C++ function overload (one with an arg, one without). On the other hand, I appreciate your thoughts and dis-assembly. I've not disassembled code ( once upon a time I had a x86 commenting disassembler) in a very many years.

              Ravings en masse^

              "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

              "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

              Z Offline
              Z Offline
              Zuoliu Ding
              wrote on last edited by
              #41

              Yea, I see your point here on preferences. When saw the subject like More Efficient, it often made me think about actual implementation details. But fine, thanks for your good explanation

              1 Reply Last reply
              0
              • J Jorgen Andersson

                if(inVal==NULL)
                {
                inVal = internalDefault;
                }

                Wrong is evil and must be defeated. - Jeff Ello

                A Offline
                A Offline
                Andre_Prellwitz
                wrote on last edited by
                #42

                C# has the null coalescing operator

                inVal = inVal ?? internalDefault;

                Or with C# 8+

                inVal ??= internalDefault;

                It doesn’t get much cleaner and clearer that that.

                1 Reply Last reply
                0
                • W W Balboos GHB

                  The difference may be slight but one of the conundrums I find myself in is using a ternary operator to handle a default vs non-default assignment. Simplified:

                  function whatEver(inVal=NULL) { // here, NULL is a default value for a function argument

                  // This ?
                  if(inVal==NULL)
                  inVal = internalDefault;

                  // or this?
                  inVal = (inVal==NULL)?internalDefault:inVal;

                  } // function whatEver(inVal=NULL)

                  The first should be a touch more efficient as it only does an assignment when necessary, but generally an insignificant difference. So - what would you do, and, do you ever pause and consider it before choosing?

                  Ravings en masse^

                  "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                  "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                  M Offline
                  M Offline
                  Myron Dombrowski
                  wrote on last edited by
                  #43

                  Keep in mind that modern optimizers are *very* good. I wouldn’t assume that your two examples are actually going to result in different compiled code. Definitely lean toward readability.

                  W 1 Reply Last reply
                  0
                  • M Maximilien

                    Make it sexy. Keep code as clean and readable as possible. In the grand scheme of things, the compiler will make it efficient whatever the way you write it.

                    CI/CD = Continuous Impediment/Continuous Despair

                    M Offline
                    M Offline
                    MichaelLuna
                    wrote on last edited by
                    #44

                    Seen to many times where efficiency is the winning choice for code that is only hit a few times. Efficiency usually only matters on code that is hit 100s of thousands of times or more. Clean Code Rules!!!!!

                    1 Reply Last reply
                    0
                    • M Myron Dombrowski

                      Keep in mind that modern optimizers are *very* good. I wouldn’t assume that your two examples are actually going to result in different compiled code. Definitely lean toward readability.

                      W Offline
                      W Offline
                      W Balboos GHB
                      wrote on last edited by
                      #45

                      It was always about readability although I did mention that it saved a step. sometimes, in what I think is the more readable version. Spread across all languages where it's a possibilitya, however, includes scripting languages and compiled versions.

                      Ravings en masse^

                      "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                      "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                      1 Reply Last reply
                      0
                      • W W Balboos GHB

                        The difference may be slight but one of the conundrums I find myself in is using a ternary operator to handle a default vs non-default assignment. Simplified:

                        function whatEver(inVal=NULL) { // here, NULL is a default value for a function argument

                        // This ?
                        if(inVal==NULL)
                        inVal = internalDefault;

                        // or this?
                        inVal = (inVal==NULL)?internalDefault:inVal;

                        } // function whatEver(inVal=NULL)

                        The first should be a touch more efficient as it only does an assignment when necessary, but generally an insignificant difference. So - what would you do, and, do you ever pause and consider it before choosing?

                        Ravings en masse^

                        "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                        "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #46

                        if(inVal==NULL)
                        {
                        inVal = internalDefault;
                        }

                        Ternary operators have their place, but aren't mean to replace "if" blocks. Also using that since the input-validation exceptions follow the same pattern, makes code nicely readable. And yes, always as blocks. Typing two chars extra isn't gonna kill anyone.

                        Bastard Programmer from Hell :suss: "If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.

                        1 Reply Last reply
                        0
                        • W W Balboos GHB

                          KateAshman wrote:

                          check what my developers commonly understand best, and pick that one.

                          I've never considered coding to be a majority operation. I do what I do because I think that's how it should be done. If I learn something better I'll fix it.

                          KateAshman wrote:

                          I've seen many many many average developers write code in a specific way because it's supposedly more efficient.

                          Seems to contradict your earlier (first) statement. Don't join the herd in a stampede of "me too!" - if everyone does everything because that's how everyone else does it then nothing will change.

                          Ravings en masse^

                          "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                          "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                          K Offline
                          K Offline
                          KateAshman
                          wrote on last edited by
                          #47

                          Coding is a team sport, even when you're alone: you need to collaborate with you from the past and you from the future. Writing code that's first and foremost efficient, while not actively improving existing code for specific performance goals, is a bad idea. I'm implying that without evidence and without specific performance goals, you should always write code that's concise and easy to understand instead. Easy to understand, however, is a moving target, which depends entirely on your team and your coding language. I've extensively researched the topic of code quality for 20+ years. YMMV

                          1 Reply Last reply
                          0
                          • W W Balboos GHB

                            The difference may be slight but one of the conundrums I find myself in is using a ternary operator to handle a default vs non-default assignment. Simplified:

                            function whatEver(inVal=NULL) { // here, NULL is a default value for a function argument

                            // This ?
                            if(inVal==NULL)
                            inVal = internalDefault;

                            // or this?
                            inVal = (inVal==NULL)?internalDefault:inVal;

                            } // function whatEver(inVal=NULL)

                            The first should be a touch more efficient as it only does an assignment when necessary, but generally an insignificant difference. So - what would you do, and, do you ever pause and consider it before choosing?

                            Ravings en masse^

                            "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                            "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #48

                            I would never want to be in a situation where I had to justify something that was redundant but looked better.

                            It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups