Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Someone told me to place my entire application strings in const instead of inline.
Why is that?
Does it improve compilation time? run time? or just code standard?
example
instead of writing:
selectSingleNode.InnerText == "SomeString"
write
selectSingleNode.InnerText == SOME_CONST
You would do this purely for maintainability and readability. Using a named constant instead of a string literal will have no performance impact whatsoever.
Maintainability
If you have multiple places in the code that require the same string literal, having them all use the same named constant makes your code a lot more maintainable. If you ever decide you need to change the value of the string literal, there is only one place you need to make the change.
Readability
Even if your string literal is used in a single place, providing a named constant may make your code more readable.
For instance, in the following sample, which version do you feel conveys the intent more clearly?
// string literals
int startIdx = someString.IndexOf("[");
int endIdx = someString.IndexOf("]");
// vs. named constants
int startIdx = someString.IndexOf(TAG_START);
int endIdx = someString.IndexOf(TAG_END);
A properly chosen name for a constant can make the code's intent clearer. But the key here is that you have to pick a good name. Too often, I'll see things like:
private const string ASTERISK = "*"; // very poor name
That is a very poorly chosen constant name that doesn't help readability one bit. The problem is that it simply states the contents of the string literal, when instead, it should be communicating what the string literal is used for.
I've seen some tests where developers have tested execution time and IL generated between using const and non-const strings. It's true there is the slightest of performance gain from using const (though insignificant unless you're working for nasa or Wall Street) the real benefits are:
You are ensuring your values are immutable.
You are defining literals in one location instead of writing them inline. If you need to change a value in the future it should be easier.
This isn't exhaustive and I'm anxious to see what others post as well. Hope this at least helps.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I had an argument with my teammate about the following.
We need to parse a symbol in a string to int(it is always a digit), this particular functionality is used in a number of places. So this can be done this way:
var a = int.Parse(str[i].ToString());
The argument was: do we need to create a function for this.
int ToInt(char c) {
return int.Parse(c.ToString());
}
that can be used:
var a = ToInt(str[i]);
My opinion is that creating such a function is bad: it gives no benefits except for typing couple characters less (no, as we have autocomplete), but such practice increase a codebase and makes code more complecated to read by introducing additional functions. My teammate's reason is that this is more convinient to call just one such function and there is nothing bad in such a practice.
Actually question relates to a general: when it is ok(if at all) to wrapp combination of 2-3-4 functions with a new function?
So I would like to hear your opinions on that.
I argee that this is mostly defined based on personal preferences. But also I would like to hear some objective factors to define a convention for such situations in our project.
There are many reasons to create a new sub-routine/method/function. Here is a list of just a few.
When the subroutine is called more than once.
If it makes your code easier to read/understand.
Personal preference.
Actually, the design can be done in many ways of course, and depends on the actual design of the whole software, readability, easy of refactoring, and encapsulation. These things are to be considered on each occasion by its own.
But on this specific case, I think its better to keep it without a function and use it as the first example for many reasons:
Its actually one line of code.
The overhead of calling a function in performance will be far more the benefit you get from making it.
The compiler itself probably will unwrap it again into the one line call if you make it a function, though its not always the case.
The benefit you get from doing so, will be mainly if you want to add error checking, TryParse, etc... in the function.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm often confused by this. I've always been taught to name numbers I use often using variables or constants, but if it reduces the efficiency of the program, should I still do it? Heres an example:
private int CenterText(Font font, PrintPageEventArgs e, string text)
{
int recieptCenter = 125;
int stringLength = Convert.ToInt32(e.Graphics.MeasureString(text, font));
return recieptCenter - stringLength / 2;
}
The above code is using named variables, but runs slower then this code:
private int CenterText(Font font, PrintPageEventArgs e, string text)
{
return 125 - Convert.ToInt32(e.Graphics.MeasureString(text, font) / 2);
}
In this example, the difference in execution time is minimal, but what about in larger blocks of code?
When they say "use constants" they literally mean "use constants"; they do not mean "use variables that never change".
This is equivalent to your code:
const int recieptCenter = 125;
int stringLength = Convert.ToInt32(e.Graphics.MeasureString(text, font));
return recieptCenter - stringLength / 2;
With the const keyword in place, the compiler knows that 125 will never change, and will be able to apply the optimizations that it would apply to a constant expressed as a literal.
There is a huge advantage to naming your "magic numbers": people who maintain your code after you leave the company would know what's the meaning of 125. It will help you, too, when you come back to revisit this code in a few years.
The difference between using variables and hard-coded values is going to be negligible at worst. Compilers deal with things like this quite well. If you saw a difference in performance I would like to hear about your methodology for collecting those metrics. (Your test itself may be suspect and most likely not repeatable.)
In any case, you should first worry about making your program correct and maintainable. That means:
Carefully naming your classes, methods and variables
Separating concerns
Avoiding magic numbers and strings (What the heck is 125 and what does it mean?)
Avoid harcoding
etc.
Also, receiptCenter does not sound like it should even be a constant. It may change infrequently but I would suggest that you store it outside of your app in a config file, or db table etc. If that value ever needs to change you have to recompile and push the whole thing to prod. Also, what about publishing your software in some other place where the value of receiptCenter is different? You just want to change a config setting, not build a different version of the app just for that instance.
Optimization is the last thing you worry about, unless it's the first thing you have to worry about and that's an architect/expert-level consideration.
receiptCenter should be a constant declared somewhere outside that private method, in some obvious place, where all your constants are declared together. Alternatively, it could be a variable read from configuration.
It really does not improve your code when you give a name to a constant number somewhere in a private method deep inside of your class library.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
which is the best memory efficient/efficient way to declare string and other data type variables in c#!?
Option 1
string strAssociateId = context.Request.QueryString["xxxxxx"],
strAssociateName = context.Request.QueryString["xxxxx"],
strPhoto = context.Request.QueryString["xxxxx"],
strDescription = context.Request.QueryString["xxxxx"];
or
Option 2
string strAssociateId = context.Request.QueryString["xxxxx"];
string strAssociateName = context.Request.QueryString["xxxxx"];
string strPhoto = context.Request.QueryString["xxxxx"];
string strDescription = context.Request.QueryString["xxxxx"];
or
any other way!?
which is the best way to follow on a longer run?!
or both have the same efficiency!?
downvoters pls comment so that i can correct.
I am just trying to find the best way and this question is not there in stackoverflow before!!
this will not lead to any discussion, and the question is completely answerable and clear
The only difference between those options, is readability. There are no performance difference, and they will generate the exact same IL.
For readability, I would choose option 2.
They will be compiled to the same IL, your Option 1 is simply syntactic sugar.
I my opinion Option 2 is better because it has better readability.
which is the best way to follow on a longer run
Both are best as both will generate the same IL.
or both have the same efficiency
Yes as both have same efficiency.
Which one to follow
You need to follow the one that is followed through out your application to support consistency. However if you are starting a new project you can decide not which one you like the most. My preference is the second one as it is more common as well as more readable
Both are better. But you are gonna mess up with the code. If you prefer using second method you might require or consider using comments
// this code is this..
So that you can know what variable or string was written here. Either you might think that this is a parameter to something.
The first method is more lovey to everybody. However I don't use strings. I use simple vars.
To follow a long run, you can use any of them. They don't have any time consuming effect.
To check more about these You can use IE F12 Developer Tools. To Test which page is using more time to get loaded.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Which is best?
private long sumVals()
{
return (dbReturn("NUns") / dbReturn("TSpd")) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
or
private long sumVals()
{
long numUnits = dbReturn("NUns");
long targetSpeed = dbReturn("TSpd");
return (numUnits / targetSpeed) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
Is it better to try and put it all onto one line, so there is less code overall, or to spread it out like in the second one?
Is one or the other quicker? Is there a benefit, eg, while compiling?
Your case is simple, so the first one is OK. But in general, I would go for the second one.
It is important that you (and others) can read the code, but you don't need to save memory (fewer lines of code as well as fewer variables).
Your code will be easier to understand and debug if you choose to write it the second way. You also don't have to have a lot of comments if your variable names explain the code well enough, which makes your code easier to read in general. (I am not telling you to stop commenting, but to write code which does not need trivial comments!)
See this question for more answers.
My rule of thumb is to include enough content to fully describe what the intent of the code is, and no more. In my opinion, assigning values to variables only to use those variables immediately is actually less readable. It communicates the flow of the program well enough, but doesn't communicate the actual intent.
If you renamed the function from dbReturn to GetDatabaseValue then I don't think I can come up with a more expressive way to write this function than:
return (GetDatabaseValue("NUns") / GetDatabaseValue("TSpd")) * 60);
This communicates the intent perfectly (notwithstanding the fact that I don't know what "NUns" and "TSpd" mean). Fewer symbols means fewer things to understand when reading the code.
Full disclosure: Including extra symbols does improve debuggability. I write this way when I am first building a function so that I can track down where things go wrong. But, when I am satisfied with the implementation, I compress it down as much as possible for my and my co-workers' sanity.
As far as I can tell, there would be no run-time performance gain achieved by either approach. Compilers are awesome - they do this inlining without your knowledge. The only difference is in the code's readability.
To me, longer is always better. Modern compilers will shrink most code to be very fast. However, being able to maintain code through lots of comments and easy-to-read code is hugely important.... especially if you are one of those guys who have to maintain someone else's code!
So, my vote is the longer version (with a comment explaining what you are doing too!)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I using c# winforms and wanted to know how it's better to write and why.
if(txtName.Text == "John")
;
or
String name = txtName.Text
if (name == "John")
;
Edit: Thanks guys you helped me a lot!!!
The second version is pointless - it is longer, less readable and introduces one extra variable (though a good compiler would get rid of it, assuming it is not used elsewhere).
Of the two choices, this one is better:
if(txtName.Text == "John")
Though I would go with a third:
if(txtName.Text.Equals("John", StringComparison.InvariantCultureIgnoreCase)
You may want the StringComparison option to be a different enumeration value, depending on how you want the comparison to occur.
For simplicity sake I would go with:
if(txtName.Text.Equals("John"))
Maybe I'm wrong, but others are answering to some complex scenario which isn't the case of one suggested by OP.
What's better?
In fact, it's the same. There's a single difference: first approach, you're storing control's text in a variable and later you check if it's equal to John. Second approach does the same thing, but it gets control's text accessing its string value directly by calling Text property.
When to use a variable and when to access to the property directly? It's just an assumption, because this will depend on each particular use case, but in common terms, call Text property directly if you're accessing its object (the text) just for checking it in a moment of time, otherwise, you'd want to store it in some variable if:
If you want to do some concatenation with Text without affecting the text held by this (if you concatenate it to the Text, you're going to modify it in your app user interface too!).
You're in a multi-threaded environment and you want to get Text in its current state because it can change since user interface is available to the user and it can change its value during some operation.
You just like variables!. If you find using variables clarifies your code better and adds meaning, why not? Nowadays' computers, even mobile phones, have a lot of memory and one, two or three variables wouldn't change anything (maybe 1KB more? wohoo!).
That's all.
Read Best Practices for Using Strings in the .NET Framework.
if (String.Equals(txtName.Text, "John", StringComparison.OrdinalIgnoreCase)) {
// ...Code.
}
For string comparison i would suggest:
string.compare(strA, strB, stringComparisonMethod)
For accessing the text it doesn't matter, the second way is more friendly but both will do the same
I think the later is better because you will be using a less variable i.e. name . Except that I don't see any difference (the styling is obviously upto yourself)
If you're using the value in other parts of your code, I'd go with defining a variable. Otherwise, use the shorter version.
In C# you don't have to use .Equals to compare strings (in response to a comment). == does the same thing.
if(txtName.Text == "John")
This is more conventional and efficient way of these you have shown.
String name = txtName.Text
if (name == "John")
;
Declaring extra variable "name" will increase the code size with any benefit except increasing the program memory. Once I tried and found declaring extra variable and assigning text to it and later accessing this variable instead of text property txtName.Text makes it less efficient then accessing through property.