Cosmetic vs More Efficient
-
I would completely disregard both causes, check what my developers commonly understand best, and pick that one. As a rule: - Never write code for an unqualified or unasked efficiency goal. - Always write code that is cost-effective to maintain. I've seen many many many average developers write code in a specific way because it's supposedly more efficient. In almost all of those cases, they completely skipped measuring performance and examining the software requirements, and are picking an obtuse implementation because it makes them feel good about their code. To be a excellent developer, you need to write excellent code for humans, and randomly add optimized of code for the compiler. The compiler doesn't care at all, while the humans do. Write code for the latter.
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.
"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
-
My God in heaven. The first thing you absolutely must fix is the spacing:
inVal = (inVal == NULL) ? internalDefault : inVal;
That's better. Now, what were you babbling on about?
Software Zen:
delete this;
Gary Wheeler wrote:
That's better. Now, what were you babbling on about?
Shoes and Ships and Sealing Wax. Cabbages and Kings.
"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
-
This was not intended to be a C++ only question. The C++ on the top of the block is incidental to my picking a code block (should have used plain code).
"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
Besides my uncalled for nitpicking on syntax, the more important point of my answer was the idea of avoiding arbitrary "flag" values in parameters. This goes along the lines of "Principle of least astonishment"[^] or "minimum surprise principle" as I prefer to call it, of not forcing the user of your code to remember artificial conventions. For instance, if you have in your .h file a function:
string find_question (int answer=-1);
You have to go to the source file (or the docs) to find behind it some code like:
string find_question (int answer)
{
if (answer == -1)
answer = 42;
...
}Sometimes use of such "flag" values is hard to avoid but in many cases, specially with templetized languages, it is just laziness. One good example of such lazy design is the
basic_string
class in C++. IMO there is no excuse for using -1 (fancifully disguised asstring::npos
) as a flag for last position in string.Mircea
-
Besides my uncalled for nitpicking on syntax, the more important point of my answer was the idea of avoiding arbitrary "flag" values in parameters. This goes along the lines of "Principle of least astonishment"[^] or "minimum surprise principle" as I prefer to call it, of not forcing the user of your code to remember artificial conventions. For instance, if you have in your .h file a function:
string find_question (int answer=-1);
You have to go to the source file (or the docs) to find behind it some code like:
string find_question (int answer)
{
if (answer == -1)
answer = 42;
...
}Sometimes use of such "flag" values is hard to avoid but in many cases, specially with templetized languages, it is just laziness. One good example of such lazy design is the
basic_string
class in C++. IMO there is no excuse for using -1 (fancifully disguised asstring::npos
) as a flag for last position in string.Mircea
I addressed this somewhere else but, as an example, a variable arg list is possible (and often very desirable) in, for example, php (very much C-like except for no strong typing). It allows one to create a function with a default value and still not be stuck with just that value. An ease of use thing. The example I gave in what is really a style-preference question, can be called either as whatEver(inVal) or whatEver() with the latter not giving a 'missing argument' error but rather defaulting to what was in the declaration. An example of use: initializing a random function: with a value it uses that; without a value it can internally pick the current time of day. It's related somewhat to C++ overloading functions.
"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
-
if(inVal==NULL)
{
inVal = internalDefault;
}Wrong is evil and must be defeated. - Jeff Ello
I love the matching braces! When did they invent that???
-
I usually write:
void whatEver (int inval = internalDefault)
I want to let users see what the function does in case of a NULL value. Otherwise I would have to document what happens when parameter is NULL.
function whatever(inval=NULL)
is simply not C/C++.Quote:
do you ever pause and consider it before choosing
I consider every line in my programs. This would be no exception. EDIT: Note that in C++ default value is written in the header file or wherever the function is declared not in the implementation as your code seems to suggest.
Mircea
TBH, if it is something we have to do a lot of, I prefer wrapping it with a #defined function...
void fx(int intVal)
{
intVal = COALESCE( intVal, intValDefault );
intVal = COALESCE( intVal, intValDefault );
intVal = COALESCE( intVal, intValDefault );
intVal = COALESCE( intVal, intValDefault );
intVal = COALESCE( intVal, intValDefault );
}Stealing the syntax from SQL gets the point across. Sometimes, doing something 5 times in a row, changes your interpretation of the value of the choice.
-
I usually write:
void whatEver (int inval = internalDefault)
I want to let users see what the function does in case of a NULL value. Otherwise I would have to document what happens when parameter is NULL.
function whatever(inval=NULL)
is simply not C/C++.Quote:
do you ever pause and consider it before choosing
I consider every line in my programs. This would be no exception. EDIT: Note that in C++ default value is written in the header file or wherever the function is declared not in the implementation as your code seems to suggest.
Mircea
I agree with this. If your default parameter is only going to be replaced anyway, just go straight to the replacement. Of course, you still need to allow for null actually being passed (assuming the parameter is of a nullable type), so you'll need the check internally. I'm ambivalent on the question of ternary vs 'standard' here. The ternary is small and uncomplicated enough to be readable. Personal/team preference there.
-
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?
"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
I would always use the first set of code (marked by "this ?") for two reasons... 1) I haven't bothered to learn all the new ways of coding for the simple reason that they most often make the code look arcane and difficult to read. This would result in boosting maintenance costs through difficulties with less experienced developers trying to understand what has been written. 2) Efficiency is highly overrated in computer systems. Do you really believe that a Human Being will be able to tell the difference in speeds between the two types of code? Of course not. So why bother with it? The reason developers bother with such concoctions is they are under the impression that what they are doing either looks "cool", they actually believe that using such arcane coding constructs will make their applications perform better, or both. As to the latter, no such coding construct will make one's code perform better except in the tiny recesses of computer memory where no one will ever notice.
Steve Naidamast Sr. Software Engineer Black Falcon Software, Inc. blackfalconsoftware@outlook.com
-
I love the matching braces! When did they invent that???
Rusty Bullet wrote:
I love the matching braces! When did they invent that???
Probably 'they' invented it c1970 but I suspect it had been used earlier. See Indentation style - Wikipedia[^] for Allman braces and match the date with BSD Berkeley Software Distribution - Wikipedia[^] It is definitely the way I was shown for Algol 60 (although the braces were then tokens called begin and end) and the one that I have used ever since. Many other folks have independently 'invented' it. If K&R's bracing is TOOTBS (The One and Only True Brace Style, Allman's bracing is TOOLBS (The One and Only Logical Brace Style) or TOOSBS (The One and Only Sensible Brace Style). Much, much, much easier for matching starts and ends of blocks; much, much, much easier for finding mismatched braces.
-
I would always use the first set of code (marked by "this ?") for two reasons... 1) I haven't bothered to learn all the new ways of coding for the simple reason that they most often make the code look arcane and difficult to read. This would result in boosting maintenance costs through difficulties with less experienced developers trying to understand what has been written. 2) Efficiency is highly overrated in computer systems. Do you really believe that a Human Being will be able to tell the difference in speeds between the two types of code? Of course not. So why bother with it? The reason developers bother with such concoctions is they are under the impression that what they are doing either looks "cool", they actually believe that using such arcane coding constructs will make their applications perform better, or both. As to the latter, no such coding construct will make one's code perform better except in the tiny recesses of computer memory where no one will ever notice.
Steve Naidamast Sr. Software Engineer Black Falcon Software, Inc. blackfalconsoftware@outlook.com
Efficiency is not highly overrated, depending upon the type of coding you do. Even early on I had some molecular modeling code that, when I changed from function (actually subroutine) return values to global values ran about 95% faster. Overnight batch runs became real-time in terms of excitation and planning the next iteration target. OK - long ago with FORTRAN and room-size computers. And time sharing. Some other optimizations were made for I/O timing, as well. Back to now: doing it right, which means efficient coding, is even necessary for Web-Based applications: whether it's load time for a page (one second or fifteen?) or, far more importantly, optimizing SQL: something which has reared it's head, recently, as the amount of data in tables, especially joined tables, has grown. A stored procedure could even fail do to exceeding the maximum execution time set up (again, 400 users means limits). So - if all your coding has to handle is small numbers of iterations and much time awaiting human responses it makes no perceivable difference - but good habits pay one back when they don't have to what always seems to be the inevitable future of a good application.
"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
-
Rusty Bullet wrote:
I love the matching braces! When did they invent that???
Probably 'they' invented it c1970 but I suspect it had been used earlier. See Indentation style - Wikipedia[^] for Allman braces and match the date with BSD Berkeley Software Distribution - Wikipedia[^] It is definitely the way I was shown for Algol 60 (although the braces were then tokens called begin and end) and the one that I have used ever since. Many other folks have independently 'invented' it. If K&R's bracing is TOOTBS (The One and Only True Brace Style, Allman's bracing is TOOLBS (The One and Only Logical Brace Style) or TOOSBS (The One and Only Sensible Brace Style). Much, much, much easier for matching starts and ends of blocks; much, much, much easier for finding mismatched braces.
TOOTBS is for me. Staggered braces were invented by publishers trying to squeeze more code on a page to save paper. It was anti-readable. The problem with squeezing the code for publishing was that people learned from books, and learned the wrong style. Publishing should remain as publishing and readable code should be the norm for actual coding, but then I am opinionated toward readability and maintainability.
-
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?
"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
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: retFixNullArg_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: retFixNullArg_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: retFixNullArg_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: retFixNullArg_IsNullOrWhiteSpace:
IL_0 -
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?
"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
-
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?
"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
-
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?
"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
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. -
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.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.
"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
-
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.
"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
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
-
if(inVal==NULL)
{
inVal = internalDefault;
}Wrong is evil and must be defeated. - Jeff Ello
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.
-
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?
"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
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.
-
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
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!!!!!