Converting IF statements to simple statement - Which one is efficient? [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I hope everyone will enjoy reading this.
I have two IF statements below
public int GetTax(Item item)
{
int tax=0;
if(item.Name.Equals("Book"))
{
tax = 10;
}
if(item.Imported)
{
tax += 5;
}
return tax;
}
I have converted above if condition to this.
public int GetTax(Item item)
{
return 5 * ((int)item.Name.Equals("Book") * 2 + ((int)item.Imported));
}
Which one do you think efficient? and justify why?

If compiled literally the 2nd method is more efficient, because there is no branching.
Whenever there is branching, there is some branch prediction, which could miss, and therefore cause the CPU to re-execute the machine instructions.
Having said that, depending on the compiler, what you have written may be simple enough for it to optimize to equivalent code. This does depend on the return type of what you call. If the return type is boolean, they are equivalent.
However, if for example, item.Imported is actually of integer type, then the two examples you gave are not equivalent, and the compiler may not compile both to the same thing.
Because optimization is very compiler-dependent. If it was important to minimize runtime, you will only know for sure if you benchmark the code.

Related

How to safely and cleanly rewrite critical/production code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have some critical production routines need to be rewritten from scratch. Take a simple example:
public class ProductionClass {
public IList<Values> WillBeFiredIfThisBreaks(Input input) {
...
}
}
The input object has way too many permutations to unit test thoroughly, and I want to play it safe because these routines are heavily used everyday. So, my thought was to:
1) Rename and mark the current implementation as obsolete.
2) Write a new implementation that falls back on the old one if there are any issues (see below)
3) Remove the old implementation after the new one has been running in prod for a month or two without issues.
public class ProductionClass {
public IList<Values> WillBeFiredIfThisBreaks(Input input) {
try{
var ret = NewImpl(input);
} catch(Exception){
ret = null;
}
if(ret == null || ret.Count == 0){
Log.Error("NewImpl Failed! Inputs: {0}", inputs);
return OldImpl(input);
}
return ret;
}
public IList<Values> NewImpl(Input input) {
...
}
[Obsolete("Rewritten 03/18/2013, throw away once NewImpl confirmed stable", false)]
public IList<Values> OldImpl(Input input) {
...
}
}
The above approach is a bit ugly in that I'll have to go through and recreate this logic for every method that I need to rewrite. (And I'll correspondingly need to remove the fallback logic and delete the obsolete methods in every location when the new code is confirmed stable). So my question is: Are there any .NET frameworks or design patterns which make this sort of "ultra-paranoid" code rewrite a bit more elegant?
Since you ask for a pattern, a possible response is to use AOP with method weaving. But a better response would be concentrate your effort in creating the unit test.

Linq Any() vs foreach [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Just wonder which approach is faster and better to use or which do you prefer
bool userHavePermission = user.Permissions.Any(x => x.UpperName == "ADMINISTRATOR");
or
foreach (Permission p in _Permissions)
{
if (p.UpperName == name.ToUpper())
return true;
}
return false;
Thanks
It's almost same code, the only difference being that with the second code snippet you're gonna get a NullReferenceException at runtime if the name variable is null because you will be calling the .ToUpper() method on a null instance. The first looks shorter, safer and more readable, it's what I would use. And to ensure that there won't be any NREs:
return user
.Permissions
.Any(x => string.Equals(x.UpperName, name, StringComparison.OrdinalIgnoreCase));
Using Any is the better approach as it is one line. It reads easier and takes up less space.
Additionally it is unclear what the Permissions object is but if it's a entity of somekind representing a database table then Any is definitely better as you only return the result of the query where the foreach is going to resolve the entire list of Permissions before the iteration begins.

What is the preferred coding style for checking if something is false? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Given the following:
bool isCorrect = theAnswer == 42;
Which is the preferred way of testing false boolean logic in C# (programming in general)?
if (!isCorrect)
// throw exception
or
if (isCorrect == false)
// throw exception
The reason I ask is because one of our senior developers at work suggests we should always use the latter approach as it enhances readability and ensures other developers can clearly see the false check; an exclamation mark is easy to miss. I much prefer the former as it's more concise and readable enough to me.
I understand that this may be a subjective issue so was wondering if there was a concrete preference mentioned in any coding style.
I have seen production code from senior developers containing such code:
if (isCorrect.ToString().Length == 5)
But I'm still using:
if (!isCorrect)
Use what you think is more readable for you, there is no statistics among all developers))
The preferred way (I'm not sure if it actually is a best practice, but it definitely should be) is to not test false
// First question: "Is the answer correct ?"
bool isCorrect = theAnswer == 42;
// Second question: "What if it is ?"
if (isCorrect)
{
}
else //Third question: "What if it isn't ?"
{
}
It's not only more logical, but saves you from scrolling around to skip error handling if you need to follow the actual flow of your code.
Also, it's worth pointing out for completeness that boolean names should always be positive: think isCorrect VS isNotWrong ... isPositive VS isNotNegative ... much easier not only to read but to understand too.
Given the following:
bool isCorrect = theAnswer == 42;
The clearest way to check the inverse is (IMHO!):
bool isWrong = !isCorrect;
...
if (isWrong)
// throw exception
You are right that (!condition) is more concise.
The senior dev is right that (condition == false) is more 'visible' (or readable if you like).
Since it just boils down to preference, you should just do what the senior dev suggests and keep everything consistent whether you like it or not. When you are the senior dev you can go back and change everything.

C# : Proper "if - elseif" formatting [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I frequently run into the following problem, I was wondering if there is any better way to deal with it:
if (A || B)
{
//Start stuff if either A or B is true. Then:
if (A && B)
//DoSomething
else if (A && !B)
//DoSomething
else if (B && !A)
//DoSomething
}
I'm asking because the if-elseif-elseif eventually looks like a big mess to read through, when the comments are replaced by code. Not even talking about what to do when theres a C involved. Any help is welcome~
At the very least, the two last conditions are a bit redundant and can be simplified:
if (A && B)
//DoSomething
else if (A)
//DoSomething
else if (B)
//DoSomething
Since we already know that both cannot be true. Apart from that, I don’t see how this could be simplified much further. Since you are essentially interested in each permutation of cases, you fundamentally need to treat them all.
This can't really be answered, but anyway, here are some thoughts:
Use Polymorphism
Factor out methods

Where can I learn the ins and outs of enumerators in C#? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is there a good resource out there that explains the concept of enumerators and custom enumerators? Particularly one with a good solid example of why you would want to implement IEnumerable yourself and how you would use it effectively?
I occasionally come across yield and I am trying to get a better understanding of it.
The easiest example:
IEnumerable<string> GetNames()
{
yield return "Bob";
yield return "Bob's uncle";
yield return "Alice";
yield return "Stacy";
yield return "Stacy's mom";
}
Usage:
foreach (var name in GetNames())
{
Console.WriteLine(name);
}
To see it in action, place a debugger breakpoint on every line in the GetNames method.
Another book I found quite useful when I was learning about IEnumerable and IEnumerator is Troelsen's Pro C# 2008 book. It explains what the interfaces contain and how to build iterators with the "yield" keyword.
Hope this help.
Here are a couple more resources for after you've gotten the basics down.
Wes has a great article on the performance characteristics of iterators:
http://blogs.msdn.com/wesdyer/archive/2007/03/23/all-about-iterators.aspx
If you have questions about why there are so many weird restrictions on what you can do in an iterator block, here's my seven part series on what motivated the unusual rules:
http://blogs.msdn.com/ericlippert/archive/tags/Iterators/default.aspx
The best example and reference I found is actually in the C# in Depth book from the almighty Jon Skeet. It's not too costly and it's worth it for everything you'll learn about C#.
A good sample can be found at the MSDN page for IEnumerable.

Categories

Resources