473,387 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

C# coding guidelines: use "this." or not when referring to member fields/properties within the object?

I'm never quite sure whether to use "this." or not when referring to fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of the
same class and is not declared in the method as a local variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?
Apr 21 '06 #1
60 4959

I use this. Its just easier to maintain. Its not easier to type everytime,
but easier to come back to later.
Because I know when I'm authoring the code ... that its a member variable.
Editing,maintaining ...sometimes you might forget.

Go and google "brad abrams" "naming conventions".

...

On occasion,,, when I wrote vb.net code. I use the "Me." keyword. It looks
like crap, but its the same mentality as this.
vb'ers don't understand it... and I'm just like "its like java and c# with
the this word"

I dislike vb.net.... its just not as clean to me.

I do not like when people use the same names for their parameter/arg list...
and the member variable

public class Emp
private int empid;

public Emp ( int empid )//constructor
this.empid = empid;
I hate that crap. I also dont like

Exception exception = new Exception("bad");

when the only difference between the object and the variable is the case.

Anyways..... there are my thoughts.

I use m_empid ... I dont' really like the _empid .. but to each his own.

There are no 100% right answers all the time. One time I emailed Brad..and
he was just like "pick one and go with it".

...
"Dave" <no**@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
I'm never quite sure whether to use "this." or not when referring to fields or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code easier to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of the
same class and is not declared in the method as a local variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

Apr 21 '06 #2

"Dave" <no**@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
I'm never quite sure whether to use "this." or not when referring to
fields or properties in the same class. It obviously works just fine
without it but sometimes I wonder if using this. consistently may make the
code easier to understand for someone else, etc. Using "this." makes it
immediately clear, for example, that the variable being referred to is a
member of the same class and is not declared in the method as a local
variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?


I use a prefix for member variables so that I know by sight that the
variable I'm referencing is a member variable and not a local.

public class SomeClass
{
private int mMyInt;
public SomeClass() {
mMyInt = 5;
}
public int MyInt {
get {
return mMyInt;
}
set {
mMyInt = value;
}
}

public int Add(int Value)
{
return mMyInt + Value;
}
}

For the "this" keyword, I use when I "need" to use the property instead of
the member. For example, I create properties for non-member variables (such
as values stored in the Request property in web-based applications).

....
public int RecordId {
get {
object o = Request("id");
if (o == null) {
return 0;
} else {
return (int) o;
}
}
}
....

By doing this, I don't have to write code to perform the check. Heck, I
don't even have to remember the "id" key, just this.RecordId. Now, this is
where the "this" comes in for us. We use "this" when we access properties,
but not members. Because the "m" prefix for members allows us to identify
the variable as a member, we don't need "this" to further identify it. For
local variables, our shop-standards require they be camelcased while
parameter names are pascalcased.

This is our standard for our shop, not everyones choice (and the parameter
being pascal cased instead of camel cased is against the Capitalization
Conventions for the .Net Framework....)

See: http://msdn2.microsoft.com/en-US/lib...02(VS.80).aspx

HTH :)

Mythran

Apr 21 '06 #3
I use "this." everywhere for clarity. It just helps me know what is a
field of the current class and what isn't, particularly when I'm
staring at paper printouts on the bus. :-)

The second question is one of functionality, as you pointed out.
Usually you want to work directly with the field, since it's part of
your private state. However, sometimes you want the property, because
you want extra functionality that it provides. It all depends upon your
design and what's going on in your class.

Apr 21 '06 #4
On Fri, 21 Apr 2006 16:12:44 -0400, Dave wrote:
I'm never quite sure whether to use "this." or not when referring to fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of the
same class and is not declared in the method as a local variable.


If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight. When i
started coding in C#, i followed these conventions and hence always used
"this" in order to make it clear that i was accessing a member variable.

I then got tired of it and reverted to prefixing all my member variables
with "m_". It's ugly but at least it makes it immediately obvious to
anybody that a member variable is being involved and it removes the need
for the "this" (that you can far too easily forget to type).

Whether or not you're using "this" in your programs really depends on the
naming conventions you've chosen to follow.
Apr 21 '06 #5
Mehdi <vi****@REMOVEME.gmail.com> wrote:
If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight.


Where does MS specify the local variable and non-public member variable
guidelines?

I'm aware of http://tinyurl.com/2cun but that doesn't include member
variables or local variables.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 21 '06 #6
It makes no difference to the compiler. Use it to make your code easier to
read, and when it will do so.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Dave" <no**@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
I'm never quite sure whether to use "this." or not when referring to
fields or properties in the same class. It obviously works just fine
without it but sometimes I wonder if using this. consistently may make the
code easier to understand for someone else, etc. Using "this." makes it
immediately clear, for example, that the variable being referred to is a
member of the same class and is not declared in the method as a local
variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

Apr 21 '06 #7
On Fri, 21 Apr 2006 22:47:02 +0100, Jon Skeet [C# MVP] wrote:
Mehdi <vi****@REMOVEME.gmail.com> wrote:
If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight.


Where does MS specify the local variable and non-public member variable
guidelines?

I'm aware of http://tinyurl.com/2cun but that doesn't include member
variables or local variables.


There's this <http://msdn2.microsoft.com/en-US/library/ms229012.aspx> but
it indeed only mentions public and protected fields. I might have read the
naming convention documents a bit to quickly at the time. But i'm pretty
sure that most sample .NET code and applications i've seen from Microsoft
used camel casing without any prefix for private variables (i agree that
this does not mean that this is a general convention).
Apr 21 '06 #8
this is silly. I only use it to direct all constructor to one
'master'-constructor.

In the book Programming .NET Components from O'Reilly, Appendix E gives a C#
coding standard. A quick scan over it didn't reveal any use of this.

I'm never quite sure whether to use "this." or not when referring to
fields or properties in the same class. It obviously works just fine
without it but sometimes I wonder if using this. consistently may make the
code easier to understand for someone else, etc. Using "this." makes it
immediately clear, for example, that the variable being referred to is a
member of the same class and is not declared in the method as a local
variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

Apr 21 '06 #9
Actually, you're right. It's on page 277 in "Framework Design Guidelines."

"Mehdi" <vi****@REMOVEME.gmail.com> wrote in message
news:1s******************************@40tude.net.. .
On Fri, 21 Apr 2006 22:47:02 +0100, Jon Skeet [C# MVP] wrote:
Mehdi <vi****@REMOVEME.gmail.com> wrote:
If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight.


Where does MS specify the local variable and non-public member variable
guidelines?

I'm aware of http://tinyurl.com/2cun but that doesn't include member
variables or local variables.


There's this <http://msdn2.microsoft.com/en-US/library/ms229012.aspx> but
it indeed only mentions public and protected fields. I might have read the
naming convention documents a bit to quickly at the time. But i'm pretty
sure that most sample .NET code and applications i've seen from Microsoft
used camel casing without any prefix for private variables (i agree that
this does not mean that this is a general convention).

Apr 21 '06 #10
I prefer an underscore prefix to using "this." for fields. The problem I had
was that I'd forget to use it consistently, and I'd see a field and think it
was a local variable.

"Dave" <no**@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
I'm never quite sure whether to use "this." or not when referring to
fields or properties in the same class. It obviously works just fine
without it but sometimes I wonder if using this. consistently may make the
code easier to understand for someone else, etc. Using "this." makes it
immediately clear, for example, that the variable being referred to is a
member of the same class and is not declared in the method as a local
variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

Apr 21 '06 #11
I use the "this" keyword extensively. Especially since if I am having a
Senior Moment and I type "this." Intellisense gives me a wonderful
recuperative experience.
;-)
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Dave" wrote:
I'm never quite sure whether to use "this." or not when referring to fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of the
same class and is not declared in the method as a local variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

Apr 21 '06 #12
"Dave" <no**@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.


You should do whatever is appropriate for each situation but favour the
private variable for sure. There is no point repeatedly calling a property
to do the same thing unless there is a good reason.

Michael
Apr 22 '06 #13
Hey, I do that too!

--
:-D,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Peter Bromberg [C# MVP]" <pb*******@yahoo.nospammin.com> wrote in message
news:5E**********************************@microsof t.com...
I use the "this" keyword extensively. Especially since if I am having a
Senior Moment and I type "this." Intellisense gives me a wonderful
recuperative experience.
;-)
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Dave" wrote:
I'm never quite sure whether to use "this." or not when referring to
fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code
easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of
the
same class and is not declared in the method as a local variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores
the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

Apr 22 '06 #14
Michael C <no****@nospam.com> wrote:
"Dave" <no**@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.
You should do whatever is appropriate for each situation but favour the
private variable for sure.


I completely disagree.
There is no point repeatedly calling a property
to do the same thing unless there is a good reason.


For me, a good reason is: "there may not be any validation now, but I
suspect there might be in the future".

If all your code accesses the data via the property, you know there's
only one place where it's set, so you can always put the validation
there. You can also add a normal breakpoint to find out when it's set.
(IIRC in VS 2005 there are breakpoints for when variables change value
- I haven't tried to use them yet. I suspect they're not quite as easy
as just clicking on the bar on the appropriate line though :)

This is why I've got a feature request in for variables which are
compiled to normal private fields, but from C#'s point of view are
private to the property:

public int Foo
{
int foo;

public get { return foo; }
public set { foo = value; }
}

void DoSomething()
{
// This wouldn't work
// foo = 20;

// This would be fine
Foo = 20;
}

For serialization purposes and some other special cases, you might need
some way (an attribute?) of overriding this restriction for certain
methods. (Constructors would almost certainly have to have access to
the raw variables.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 22 '06 #15
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
For me, a good reason is: "there may not be any validation now, but I
suspect there might be in the future".


It all depends on the situation but I think it is rare that the class itself
needs to access the variable though the property. There is no point turning
a high speed variable access into a slower function call every time just in
case something might change in the future. If it does change and it becomes
appropriate to use the property then modify the code.

Michael
Apr 22 '06 #16
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
For me, a good reason is: "there may not be any validation now, but I
suspect there might be in the future".
It all depends on the situation but I think it is rare that the class itself
needs to access the variable though the property.


Whereas I believe it's rare that it would need any potential speed
increases of *not* accessing the variable through the property.
There is no point turning
a high speed variable access into a slower function call every time just in
case something might change in the future.
What makes you think that the property access would be slower? The JIT
is quite capable of inlining property access - and if the property
setter does significant work which would prevent inlining, then chances
are you want that validation etc to take place on every set anyway. I
believe that bypassing the property for the sake of micro-optimisation
is a bad idea.

The time when it makes sense to bypass the property is when you really
*want* to bypass validation, for instance if you want to set multiple
interdependent variables, and changing any one of them alone to the new
value would be invalid. That should be the exception, not the rule.
If it does change and it becomes appropriate to use the property then
modify the code.


Why store up work for later? It's just as *easy* to use the property as
the variable when you first write the code, and gives immediate
advantages in terms of simplicity of debugging, IMO.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 22 '06 #17
> There is no point turning a high speed variable access into a slower function call every time just in case something might change in the future.

Only in debug mode. One of Bruce's Laws is "never try to
micro-optimize... the compiler is much smarter than you are!" :-)

In this case, somewhere in the compiler / JITter sequence the call to
the property getter is reduced to a simple variable access, so there is
no difference in performance whatsoever for release-compiled code.

That said, I'm not sure I agree with Jon. The property setter may
include functionality that you explicitly *don't* wan't to invoke from
within the class, like raising ...Changed events and things like that.
It all depends upon what you're doing and why, and how you want to
timing of things to work out. I have plenty of classes that want to
manipulate their state in some way and _only then_ determine which
....Changed events to raise as a result. I have other classes that
always set their own fields through the property setters specifically
in order to invoke additional behaviour such as ...Changed events.

It all depends upon what the setter does and what your class is trying
to do.

Apr 22 '06 #18
Forget senior moments - intellisense elliminates tyops.... I mean typos!
Also, with forms, I often forget what everything is called (this is why I
like prefixes for fields).

"Peter Bromberg [C# MVP]" <pb*******@yahoo.nospammin.com> wrote in message
news:5E**********************************@microsof t.com...
I use the "this" keyword extensively. Especially since if I am having a
Senior Moment and I type "this." Intellisense gives me a wonderful
recuperative experience.
;-)
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Dave" wrote:
I'm never quite sure whether to use "this." or not when referring to
fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code
easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of
the
same class and is not declared in the method as a local variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores
the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

Apr 22 '06 #19
On Sat, 22 Apr 2006 17:10:46 +1000, "Michael C" <no****@nospam.com>
wrote:
It all depends on the situation but I think it is rare that the class itself
needs to access the variable though the property. There is no point turning
a high speed variable access into a slower function call every time just in
case something might change in the future. If it does change and it becomes
appropriate to use the property then modify the code.


That's a recipe for disaster, and doesn't make a lot of sense to boot.
If the setter is trivial, it will be inlined -- hence there won't be a
slow function call at all! And if the setter isn't trivial, you had
better make sure to call it anyway.

You should only ever directly set a backer variable in the constructor
of if you specifically wish to bypass whatever the setter does, and in
that case this purpose should be documented.
--
http://www.kynosarges.de
Apr 22 '06 #20
On Sat, 22 Apr 2006 10:04:09 +0200, Christoph Nahr
<ch************@kynosarges.de> wrote:
of if you


Sigh, that should read "or if you"...
--
http://www.kynosarges.de
Apr 22 '06 #21

"Michael C" <no****@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
| "Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
| news:MP************************@msnews.microsoft.c om...
| > For me, a good reason is: "there may not be any validation now, but I
| > suspect there might be in the future".
|
| It all depends on the situation but I think it is rare that the class
itself
| needs to access the variable though the property. There is no point
turning
| a high speed variable access into a slower function call every time just
in
| case something might change in the future. If it does change and it
becomes
| appropriate to use the property then modify the code.
|
| Michael
|
|

But that's the whole point, there is no slower access when you access the
property, the JIT will inline the property getter, so the result is a simple
direct field access (memory access)
Consider following sample:

class Test
{
int i;
int v;
int I {
get { return i;}
}
static void Main()
{
Random rnd = new Random();

Test t = new Test();
t.i = rnd.Next();
t.v = rnd.Next();
int iii = t.I;
int ii = t.v;
int sum = ii+iii;
Console.WriteLine(sum);
}

The JIT produces the following when run in the debugger...
' move OBJREF t into eax
00cb0115 8b45f0 mov eax,[ebp-0x10]
ss:0023:0012f470=01275ae4
' move field i value into eax !!!!
00cb0118 8b4004 mov eax,[eax+0x4]
move eax into edx
00cb011b 8bd0 mov edx,eax
' move OBJREF into eax
00cb011d 8b45f0 mov eax,[ebp-0x10]
' move field v into eax
00cb0120 8b4008 mov eax,[eax+0x8]
' add i to v store result in eax
00cb0123 03c2 add eax,edx
' move result into esi
00cb0125 8bf0 mov esi,eax
' use value in esi as argument for Console.WriteLine..
you see, the property getter and setter (in this simple case, is nothing
else than syntactic sugar, there is no such thing at the machine code level
as a (slower) function call.
Willy.


Apr 22 '06 #22
On Fri, 21 Apr 2006 15:09:51 -0700, "James Park" <fa******@fakeaddress.com>
wrote:
I prefer an underscore prefix to using "this." for fields. The problem I had
was that I'd forget to use it consistently, and I'd see a field and think it
was a local variable.

"Dave" <no**@nowhere.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
I'm never quite sure whether to use "this." or not when referring to
fields or properties in the same class. It obviously works just fine
without it but sometimes I wonder if using this. consistently may make the
code easier to understand for someone else, etc. Using "this." makes it
immediately clear, for example, that the variable being referred to is a
member of the same class and is not declared in the method as a local
variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?


I also like the underscore to id private fields. It lets you use the same name
for things.

private int _ndx;

public void SomeMethod(int ndx)
{
_ndx = ndx;
}

Public int Ndx
{
get
{
return _ndx;
}
set
{
_ndx = value;
}
}
Good luck with your project,

Otis Mukinfus
http://www.arltex.com
http://www.tomchilders.com
Apr 22 '06 #23
On Fri, 21 Apr 2006 21:48:50 -0400, "Kevin Spencer"
<ke***@DIESPAMMERSDIEtakempis.com> wrote:
Hey, I do that too!


You guys be careful. You're not allowed to have senior moments unless you have
a white beard like me ;o)

Good luck with your project,

Otis Mukinfus
http://www.arltex.com
http://www.tomchilders.com
Apr 22 '06 #24
Bruce Wood <br*******@canada.com> wrote:

<snip>
That said, I'm not sure I agree with Jon. The property setter may
include functionality that you explicitly *don't* wan't to invoke from
within the class, like raising ...Changed events and things like that.
And if you *explicitly* don't want that, then that's fine. I just think
it's worth making that decision specifically, but defaulting to using
the properties unless you've got a reason not to.

<snip>
It all depends upon what the setter does and what your class is trying
to do.


Agreed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 22 '06 #25
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Whereas I believe it's rare that it would need any potential speed
increases of *not* accessing the variable through the property.
I try to make things quick straight off the bat (without going overboard
obviously). If there are 2 methods that are practically the same I will go
for the faster method.
What makes you think that the property access would be slower? The JIT
is quite capable of inlining property access - and if the property
setter does significant work which would prevent inlining, then chances
are you want that validation etc to take place on every set anyway. I
believe that bypassing the property for the sake of micro-optimisation
is a bad idea.
Have you confirmed this? If the property doesn't get inlined then the speed
different with all the pushes and pops could be significant.
The time when it makes sense to bypass the property is when you really
*want* to bypass validation, for instance if you want to set multiple
interdependent variables, and changing any one of them alone to the new
value would be invalid. That should be the exception, not the rule.
If it does change and it becomes appropriate to use the property then
modify the code.


Why store up work for later? It's just as *easy* to use the property as
the variable when you first write the code, and gives immediate
advantages in terms of simplicity of debugging, IMO.


I find that by writing the faster code to start with I save work optimising
later, which is going to be a significant saving over a few rare changes
(pretty much never in the last 10 years since I first wrote a property).

Michael
Apr 22 '06 #26
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Whereas I believe it's rare that it would need any potential speed
increases of *not* accessing the variable through the property.


I try to make things quick straight off the bat (without going overboard
obviously). If there are 2 methods that are practically the same I will go
for the faster method.


Whereas I go for the more maintainable, readable method. I prefer to
have code which clearly works and which maintenance engineers will be
able to understand.

Of course, if the difference proves itself to be *significant* and a
problem, that's a different matter - but otherwise the optimisation is
just premature in this kind of case.
What makes you think that the property access would be slower? The JIT
is quite capable of inlining property access - and if the property
setter does significant work which would prevent inlining, then chances
are you want that validation etc to take place on every set anyway. I
believe that bypassing the property for the sake of micro-optimisation
is a bad idea.


Have you confirmed this? If the property doesn't get inlined then the speed
different with all the pushes and pops could be significant.


Yes, I've confirmed it, several times.
Why store up work for later? It's just as *easy* to use the property as
the variable when you first write the code, and gives immediate
advantages in terms of simplicity of debugging, IMO.


I find that by writing the faster code to start with I save work optimising
later, which is going to be a significant saving over a few rare changes
(pretty much never in the last 10 years since I first wrote a property).


Premature micro-optimisation is widely regarded as a bad idea. In this
case, you aren't even actually optimising anything anyway.

See http://www.interact-sw.co.uk/iangblo...1/09/profiling for a
good article about this kind of thing.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 22 '06 #27
>> > Whereas I believe it's rare that it would need any potential speed
> increases of *not* accessing the variable through the property.


I try to make things quick straight off the bat (without going overboard
obviously). If there are 2 methods that are practically the same I will
go
for the faster method.


Whereas I go for the more maintainable, readable method. I prefer to
have code which clearly works and which maintenance engineers will be
able to understand.

Of course, if the difference proves itself to be *significant* and a
problem, that's a different matter - but otherwise the optimisation is
just premature in this kind of case.

The very best tip about optimization is: don't optimize.

If you compile from the command line, you can set a switch whether you want
the code optimized for size (small size but s--l--o--w) or for speed (BIG
and lightning fast). I deliberatly take it to the extreme, your code will be
quick and not-to-bulgy, but the point is that the compiler can do your
optimizations better and smarter than you can, and less error prone, while
you, as a programmer, can organize and document your code than the computer
can.

So focus on what you're best at, and leave the risky bussiness of
optimization to the computer that, again, will do a better job than you.
Apr 22 '06 #28
Martijn Mulder <i@m> wrote:
The very best tip about optimization is: don't optimize.
Well, don't optimise before you know there's a problem. Optimise the
*architecture* rather than optimising the code.
If you compile from the command line, you can set a switch whether you want
the code optimized for size (small size but s--l--o--w) or for speed (BIG
and lightning fast).


That's true (or used to be) for C/C++, but it isn't true for C#.
There's just "optimise - yes or no" basically (and another switch for
how much debugging information you want, if any).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 22 '06 #29
Good point about printouts. I think I'm convinced. I'll start using this.
everywhere.

As the other guy said, as with most coding conventions, the most important
thing is to be consistent.
"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@t31g2000cwb.googlegr oups.com...
I use "this." everywhere for clarity. It just helps me know what is a
field of the current class and what isn't, particularly when I'm
staring at paper printouts on the bus. :-)

The second question is one of functionality, as you pointed out.
Usually you want to work directly with the field, since it's part of
your private state. However, sometimes you want the property, because
you want extra functionality that it provides. It all depends upon your
design and what's going on in your class.

Apr 22 '06 #30
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
Whereas I go for the more maintainable, readable method. I prefer to
have code which clearly works and which maintenance engineers will be
able to understand.
You're assuming fast is unmaintainable, which can be the case if you let it
be but doesn't have to be.
Yes, I've confirmed it, several times.
Fair enough, it appear that is true.
Premature micro-optimisation is widely regarded as a bad idea.
Again it can be a bad idea if you do it wrong but *every* programmer will
chose some methods because they are faster than others. I find because I
take these speed into account my code runs faster straight off the bat than
other's at my work and Idon't have to spend time optimising it later.
In this
case, you aren't even actually optimising anything anyway.


We're going to have to agree to disagree. I've been favouring the direct
access for 10 years and have had absolutely zero problems with it. You're
not going to convince me a problem exists when one doesn't.

Michael
Apr 23 '06 #31
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
Whereas I go for the more maintainable, readable method. I prefer to
have code which clearly works and which maintenance engineers will be
able to understand.


You're assuming fast is unmaintainable, which can be the case if you let it
be but doesn't have to be.


I'm not assuming it is always unmaintainable - I'm saying that where
there's a choice between maintainable and fast, I will go for
maintainable until it's been proven that that piece of code is a
bottleneck.
Yes, I've confirmed it, several times.


Fair enough, it appear that is true.
Premature micro-optimisation is widely regarded as a bad idea.


Again it can be a bad idea if you do it wrong but *every* programmer will
chose some methods because they are faster than others. I find because I
take these speed into account my code runs faster straight off the bat than
other's at my work and Idon't have to spend time optimising it later.


My reasons for favouring readability over speed until the need for
micro-optimisation has been proven are the following:

1) Code spends much more time being maintained than written. Saving
time when someone maintains code is important.

2) Only a very small proportion of the code we write ends up being
performance critical.

3) The easier it is to understand the code, the easier it is to modify
the performance-critical sections when they've been identified.
In this
case, you aren't even actually optimising anything anyway.


We're going to have to agree to disagree. I've been favouring the direct
access for 10 years and have had absolutely zero problems with it. You're
not going to convince me a problem exists when one doesn't.


I believe that unless your code is as readable as it can be except in
places where performances has *proven* to be critical, that's a problem
in itself.

Your position is the kind of one which leads people to avoid using
exceptions anywhere, based on the myth that if you occasionally throw
exceptions, your performance will plummet. It's that kind of thing that
really hurts code quality.

Your position goes against encapsulation, too - there are often times
where you could possibly get an extra little bit of performance if you
didn't care about the object model purity. Your statements suggest that
you would willingly sacrifice design for performance in that case, even
when it hasn't been shown that the performance improvement will be
significant.

You should be aware that your position is a fairly widely criticised
one, too. It's not just me that thinks it's a bad idea. See
http://billharlan.com/pub/papers/A_T...t_of_Performan
ce.html
for another post against it, including the famous quote of Donald
Knuth: "We should forget about small efficiencies, about 97% of the
time. Premature optimization is the root of all evil."

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 23 '06 #32
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
I'm not assuming it is always unmaintainable - I'm saying that where
there's a choice between maintainable and fast, I will go for
maintainable until it's been proven that that piece of code is a
bottleneck.
I'm sure you do some optimisations as you code. I'm not suggesting you
should always write everything to make it as fast as possible, just take it
into account on the way. A good example would be to put more commonly used
items at the top of a switch statement.
My reasons for favouring readability over speed until the need for
micro-optimisation has been proven are the following:

1) Code spends much more time being maintained than written. Saving
time when someone maintains code is important.

2) Only a very small proportion of the code we write ends up being
performance critical.

3) The easier it is to understand the code, the easier it is to modify
the performance-critical sections when they've been identified.
Don't get me wrong, I don't write everything for speed at the expense of
maintainability. In my opinion there is no maintainability lost accessing
the variable directly so I would chose the faster method. In fact I think it
is more maintainable. How many times would you accidentally step into a get
and then a set while debugging just to increment an int?
Your position is the kind of one which leads people to avoid using
exceptions anywhere, based on the myth that if you occasionally throw
exceptions, your performance will plummet. It's that kind of thing that
really hurts code quality.
You're using a common newsgroup technique where you take something someone
says to the extreme and then conclude it is a bad idea because it is taken
to the extreme.
You should be aware that your position is a fairly widely criticised
one, too.


I agree, but that is with your over exaggeration of my position. I'm sure
most good programmers take speed into account to some degree when writing
code. Certainly an experienced coder will produce a faster app first time
than a beginner.

Michael
Apr 23 '06 #33
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
I'm not assuming it is always unmaintainable - I'm saying that where
there's a choice between maintainable and fast, I will go for
maintainable until it's been proven that that piece of code is a
bottleneck.
I'm sure you do some optimisations as you code. I'm not suggesting you
should always write everything to make it as fast as possible, just take it
into account on the way.


There are *some* things I take account of, but not very many. I use
StringBuilder when I don't know how many things I'll be appending,
because I know the results of not doing so can be catastrophic to
performance, for example. I don't try to put things in big methods to
avoid making method calls though - indeed, I positively split big
methods up into smaller ones, even if those smaller ones won't be
called by anything else. That hurts performance a tiny amount (if the
methods are still too big to be inlined) but improves readability.
A good example would be to put more commonly used
items at the top of a switch statement.


I certainly don't do that. I put them in the most logical way for the
reader to see them. Have you ever come across a situation (in C# - not
a different language which may have different characteristics) where
the order of the cases has made a significant difference? Have you
benchmarked it?
My reasons for favouring readability over speed until the need for
micro-optimisation has been proven are the following:

1) Code spends much more time being maintained than written. Saving
time when someone maintains code is important.

2) Only a very small proportion of the code we write ends up being
performance critical.

3) The easier it is to understand the code, the easier it is to modify
the performance-critical sections when they've been identified.


Don't get me wrong, I don't write everything for speed at the expense of
maintainability. In my opinion there is no maintainability lost accessing
the variable directly so I would chose the faster method. In fact I think it
is more maintainable. How many times would you accidentally step into a get
and then a set while debugging just to increment an int?


I wouldn't accidentally do it, because I'd be doing step over instead
of step into. However, I've gone into why you *would* want to use
properties earlier in the thread. If you've provided some validation
etc in the property setter, not performing that validation should be
the exception rather than the rule.
Your position is the kind of one which leads people to avoid using
exceptions anywhere, based on the myth that if you occasionally throw
exceptions, your performance will plummet. It's that kind of thing that
really hurts code quality.


You're using a common newsgroup technique where you take something someone
says to the extreme and then conclude it is a bad idea because it is taken
to the extreme.


Well, I'm going by what you've said. Things like:

<quote>
I find that by writing the faster code to start with I save work
optimising later, which is going to be a significant saving over a few
rare changes
</quote>

That suggests that speed is the major contributor to your design
decisions, rather than maintainability. If that's not your actual
position, then we may well have less to argue about - but I hope you
can see how statements like the one above have led me to my belief.
Perhaps I should have taken more notice of your "two methods which are
practically the same" to start with.

However, do still believe that things like rearranging switch cases for
the sake of performance emphasises the wrong thing, and even if you
don't take it to an extreme, it can lead others into an extreme
position.
You should be aware that your position is a fairly widely criticised
one, too.


I agree, but that is with your over exaggeration of my position. I'm sure
most good programmers take speed into account to some degree when writing
code. Certainly an experienced coder will produce a faster app first time
than a beginner.


Not necessarily. The difference may often be that the beginner's app
will be very quick - but not actually work properly. I'd hope that an
experienced coder would concentrate on getting something working and
maintainable, only worrying about the speed of individual sections when
those sections proved to be significantly.

The areas of speed I take into account are ones of complexity - I will
try to avoid doing something O(n^2) instead of O(n) unless I know that
n will be very small. However, that is usually a case of design and
architecture rather than actual implementation, IME.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 23 '06 #34

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
> Whereas I believe it's rare that it would need any potential speed
> increases of *not* accessing the variable through the property.
I try to make things quick straight off the bat (without going overboard
obviously). If there are 2 methods that are practically the same I will
go
for the faster method.
<cut>
I find that by writing the faster code to start with I save work
optimising
later, which is going to be a significant saving over a few rare changes
(pretty much never in the last 10 years since I first wrote a property).


Premature micro-optimisation is widely regarded as a bad idea. In this
case, you aren't even actually optimising anything anyway.


Sadly, reading through any of the C#/.NET groups easily proves you wrong
(about the wide regard, not about it being a bad idea).

Or maybe it is widely regarded as being a bad thing but the people who
regard it that way have given up trying to convince the rest :-(
See http://www.interact-sw.co.uk/iangblo...1/09/profiling for a
good article about this kind of thing.

Apr 23 '06 #35
I might point out as well that optimization, in a general sense, is the
process of conserving resources. Not only are processor usage and memory
consumption resources, but resources also encompasses the money that it
costs to develop and maintain software. That is, a software vendor can only
make money if it costs less to develop and maintain the software than the
income generated by the software. We do live in the real world, where
everything has limits, including time and money. In terms of money, human
resources are a cost factor over time. The more time it takes to develop and
maintain software, the more it costs in terms of money.

So, when speaking of optimization, one is always talking about a net gain.
One cannot logically separate or prioritize one resource over another. It is
the accumulated combination of all resources that factors into the net gain.
If one does not factor in the human resources, one is highly likely to go
out of business.

This is the basis for Jon's assertions regarding maintainability and
readability. These are factors which influence the net gain, and are
therefore legitimate optimizations as well.

It's all a balancing game. Achieving the correct balance of optimizations
results in the maximum profitability of the enterprise.

The article Jon points to is spot on. I have long maintained that extra time
spent up-front in the design process ultimately leads to an overall savings
of total resources spent in the development of software. I am usually slow
to start on a project, and like a train, pick up speed as I go along. But I
will often spend several days (at least, depending upon the size of the
project) just *thinking* about it, researching, sketching ideas and talking
about it with my peers before I write a lick of code. Once I get started, I
never stop *thinking* about optimization, and admittedly perhaps spend a wee
bit too much time over it (can't be sure), but tend to not sweat the small
stuff, and I also keep an eye on the amount of time I spend doing so, in
order to pull myself away from it when necessary (which is admittedly
all-too-often).

A good developer has this innate desire to write "elegant" code. But we must
never over-indulge that desire. This is one reason I put in so many hours
that I am not paid for. I have my pride. But I don't want my company to have
to pay for it!

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
> Whereas I go for the more maintainable, readable method. I prefer to
> have code which clearly works and which maintenance engineers will be
> able to understand.


You're assuming fast is unmaintainable, which can be the case if you let
it
be but doesn't have to be.


I'm not assuming it is always unmaintainable - I'm saying that where
there's a choice between maintainable and fast, I will go for
maintainable until it's been proven that that piece of code is a
bottleneck.
> Yes, I've confirmed it, several times.


Fair enough, it appear that is true.
> Premature micro-optimisation is widely regarded as a bad idea.


Again it can be a bad idea if you do it wrong but *every* programmer will
chose some methods because they are faster than others. I find because I
take these speed into account my code runs faster straight off the bat
than
other's at my work and Idon't have to spend time optimising it later.


My reasons for favouring readability over speed until the need for
micro-optimisation has been proven are the following:

1) Code spends much more time being maintained than written. Saving
time when someone maintains code is important.

2) Only a very small proportion of the code we write ends up being
performance critical.

3) The easier it is to understand the code, the easier it is to modify
the performance-critical sections when they've been identified.
> In this
> case, you aren't even actually optimising anything anyway.


We're going to have to agree to disagree. I've been favouring the direct
access for 10 years and have had absolutely zero problems with it. You're
not going to convince me a problem exists when one doesn't.


I believe that unless your code is as readable as it can be except in
places where performances has *proven* to be critical, that's a problem
in itself.

Your position is the kind of one which leads people to avoid using
exceptions anywhere, based on the myth that if you occasionally throw
exceptions, your performance will plummet. It's that kind of thing that
really hurts code quality.

Your position goes against encapsulation, too - there are often times
where you could possibly get an extra little bit of performance if you
didn't care about the object model purity. Your statements suggest that
you would willingly sacrifice design for performance in that case, even
when it hasn't been shown that the performance improvement will be
significant.

You should be aware that your position is a fairly widely criticised
one, too. It's not just me that thinks it's a bad idea. See
http://billharlan.com/pub/papers/A_T...t_of_Performan
ce.html
for another post against it, including the famous quote of Donald
Knuth: "We should forget about small efficiencies, about 97% of the
time. Premature optimization is the root of all evil."

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Apr 23 '06 #36
> Sadly, reading through any of the C#/.NET groups easily proves you wrong
(about the wide regard, not about it being a bad idea).
You're making an assumption that because Jon discusses the low-level
characteristics of resource usage and details of technology in the platform,
that he is also overly concerned about them. This is not a logical
conclusion. While it might seem to imply this, it does not necessarily imply
this. Jon is a C# MVP, and this is a newsgroup about C#. People ask
questions about these issues, and Jon answers them. The fact that he answers
them, and that he is diligent about the details, does not mean that he
believes one should be overly-anal about optimization. In fact, I believe
that it's important to understand these low-level details of the technology
in order to excel at it, not because one is necessarily going to be
overly-anal in the development process, but because understanding the
technology intimately lends to the overall understanding and therefore
efficiency in using it.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Nick Hounsome" <Ne**@NickHounsome.Me.Uk> wrote in message
news:04********************@fe2.news.blueyonder.co .uk...
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
> Whereas I believe it's rare that it would need any potential speed
> increases of *not* accessing the variable through the property.

I try to make things quick straight off the bat (without going overboard
obviously). If there are 2 methods that are practically the same I will
go
for the faster method.
<cut>
I find that by writing the faster code to start with I save work
optimising
later, which is going to be a significant saving over a few rare changes
(pretty much never in the last 10 years since I first wrote a property).


Premature micro-optimisation is widely regarded as a bad idea. In this
case, you aren't even actually optimising anything anyway.


Sadly, reading through any of the C#/.NET groups easily proves you wrong
(about the wide regard, not about it being a bad idea).

Or maybe it is widely regarded as being a bad thing but the people who
regard it that way have given up trying to convince the rest :-(
See http://www.interact-sw.co.uk/iangblo...1/09/profiling for a
good article about this kind of thing.


Apr 23 '06 #37
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
There are *some* things I take account of, but not very many. I use
StringBuilder when I don't know how many things I'll be appending,
because I know the results of not doing so can be catastrophic to
performance, for example. I don't try to put things in big methods to
avoid making method calls though - indeed, I positively split big
methods up into smaller ones, even if those smaller ones won't be
called by anything else. That hurts performance a tiny amount (if the
methods are still too big to be inlined) but improves readability.
I would never write a big function for performance reasons :-)
I certainly don't do that. I put them in the most logical way for the
reader to see them. Have you ever come across a situation (in C# - not
a different language which may have different characteristics) where
the order of the cases has made a significant difference? Have you
benchmarked it?
If there was a genuine reason to put them in a certain order, such as the
event handler for a menu then I would. But quite often there is no real
order.
I wouldn't accidentally do it, because I'd be doing step over instead
of step into. However, I've gone into why you *would* want to use
properties earlier in the thread. If you've provided some validation
etc in the property setter, not performing that validation should be
the exception rather than the rule.
The problem is you can't always step over. If the code is

DoSomething(MyProp);

then you can't step over MyProp and into DoSomething (afaik). Besides I
always forget to step over until I'm in.
<quote>
I find that by writing the faster code to start with I save work
optimising later, which is going to be a significant saving over a few
rare changes
</quote>
I've been programming in vb6 for many years and it's much easier in vb6 to
write incredibly inefficient code. For example IIf(x=1, 5 , 10) is 50 times
slower (I tested this once) than using an if statement because the first
returns a variant and the second just deals in ints. Vb6 is full of such
traps and it's very easy to write page after page of inefficient code so
I've become much more aware of such issues. I didn't realise until I had
this conversation just how much more efficient C# is (in some ways at
least). I could easily think of 50 examples in vb6 but struggled to find one
for C#. And the one I came up with wasn't very good :-) I good example in
vb6 was I found out at one stage that "If len(SomeString) = 0" was much
faster than "If SomeString = "" " so I started using len. The 2 methods were
practically identical so why not use the faster.
That suggests that speed is the major contributor to your design
decisions, rather than maintainability. If that's not your actual
position, then we may well have less to argue about - but I hope you
can see how statements like the one above have led me to my belief.
Perhaps I should have taken more notice of your "two methods which are
practically the same" to start with.
Don't worry, I don't go out of my way and make really bad designs to make
minor optimisations.
Not necessarily. The difference may often be that the beginner's app
will be very quick - but not actually work properly. I'd hope that an
experienced coder would concentrate on getting something working and
maintainable, only worrying about the speed of individual sections when
those sections proved to be significantly.
Generally the beginners code is slower and more buggy (and took them up to
10 times longer to write it). If you find performance issues with a more
experienced coder's work it usually harder to optimise it.
The areas of speed I take into account are ones of complexity - I will
try to avoid doing something O(n^2) instead of O(n) unless I know that
n will be very small. However, that is usually a case of design and
architecture rather than actual implementation, IME.


That makes sense, the more loops a piece of code is inside the more critical
things become.

Michael
Apr 23 '06 #38
Kevin Spencer <ke***@DIESPAMMERSDIEtakempis.com> wrote:
Sadly, reading through any of the C#/.NET groups easily proves you wrong
(about the wide regard, not about it being a bad idea).


You're making an assumption that because Jon discusses the low-level
characteristics of resource usage and details of technology in the platform,
that he is also overly concerned about them.


I don't think Nick was saying that *I* was overly concerned - just that
there are plenty of people on the newsgroups who are :(

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 23 '06 #39

"Kevin Spencer" <ke***@DIESPAMMERSDIEtakempis.com> wrote in message
news:OR**************@TK2MSFTNGP04.phx.gbl...

[cut]

A good developer has this innate desire to write "elegant" code. But we
must never over-indulge that desire. This is one reason I put in so many
hours that I am not paid for. I have my pride. But I don't want my company
to have to pay for it!


Interesting.

Turn this around and imagine your company publicly saying "We don't give our
programmers enough time or money to write code that they are proud of."

It doesn't sound so good if you put it like that does it?
Apr 23 '06 #40
"Nick Hounsome" <Ne**@NickHounsome.Me.Uk> wrote in message
news:fY********************@fe1.news.blueyonder.co .uk...

"Kevin Spencer" <ke***@DIESPAMMERSDIEtakempis.com> wrote in message
news:OR**************@TK2MSFTNGP04.phx.gbl...

[cut]

A good developer has this innate desire to write "elegant" code. But we must never over-indulge
that desire. This is one reason I put in so many hours that I am not paid for. I have my pride.
But I don't want my company to have to pay for it!


Interesting.

Turn this around and imagine your company publicly saying "We don't give our programmers enough
time or money to write code that they are proud of."

It doesn't sound so good if you put it like that does it?


I do a lot of maintenance of old code. Generally, I am tasked with:
- Making a small modification
- Making small fixes
- Troubleshooting a problem

I often have to fight the urge to rewrite the whole thing.(I don't always win)
It's not that we don't want to put out quality work. But, how do I justify spending a week on a task
that should take a day. If I come across a real timebomb in the code, I do suggest the rewrite to
the higher-ups

Generally, I attempt to be as elegant as I can be within reason.
If larger modifications are scheduled, I try to include "Rewritng" into my estimate.

Elegance is nice, but it does have to be justified if it will overly inflate the cost

Just my 2 cents
Bill



Apr 23 '06 #41
> Turn this around and imagine your company publicly saying "We don't give
our programmers enough time or money to write code that they are proud
of."
Not correct. I am a perfectionist by nature. Perfection is something
unattainable in this world. I *do* write code that they are proud of. I'm
just never satisfied with "good enough." It is *me* that I'm trying to
please in my spare time!

Like I said, "I have my pride..."

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Nick Hounsome" <Ne**@NickHounsome.Me.Uk> wrote in message
news:fY********************@fe1.news.blueyonder.co .uk...
"Kevin Spencer" <ke***@DIESPAMMERSDIEtakempis.com> wrote in message
news:OR**************@TK2MSFTNGP04.phx.gbl...

[cut]

A good developer has this innate desire to write "elegant" code. But we
must never over-indulge that desire. This is one reason I put in so many
hours that I am not paid for. I have my pride. But I don't want my
company to have to pay for it!


Interesting.

Turn this around and imagine your company publicly saying "We don't give
our programmers enough time or money to write code that they are proud
of."

It doesn't sound so good if you put it like that does it?

Apr 23 '06 #42
Jeffery Richter has an annotation in the Framework Design Guidelines
book in which he recommends the m_ prefix as well. He also metions
that s_ is good prefix for static variables. I haven't adopted it yet,
but I'm seriously considering it.

Mehdi wrote:
On Fri, 21 Apr 2006 16:12:44 -0400, Dave wrote:
I'm never quite sure whether to use "this." or not when referring to fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of the
same class and is not declared in the method as a local variable.


If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight. When i
started coding in C#, i followed these conventions and hence always used
"this" in order to make it clear that i was accessing a member variable.

I then got tired of it and reverted to prefixing all my member variables
with "m_". It's ugly but at least it makes it immediately obvious to
anybody that a member variable is being involved and it removes the need
for the "this" (that you can far too easily forget to type).

Whether or not you're using "this" in your programs really depends on the
naming conventions you've chosen to follow.


Apr 23 '06 #43
Michael C <no****@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
There are *some* things I take account of, but not very many. I use
StringBuilder when I don't know how many things I'll be appending,
because I know the results of not doing so can be catastrophic to
performance, for example. I don't try to put things in big methods to
avoid making method calls though - indeed, I positively split big
methods up into smaller ones, even if those smaller ones won't be
called by anything else. That hurts performance a tiny amount (if the
methods are still too big to be inlined) but improves readability.
I would never write a big function for performance reasons :-)


Goodo.
I certainly don't do that. I put them in the most logical way for the
reader to see them. Have you ever come across a situation (in C# - not
a different language which may have different characteristics) where
the order of the cases has made a significant difference? Have you
benchmarked it?


If there was a genuine reason to put them in a certain order, such as the
event handler for a menu then I would. But quite often there is no real
order.


In C# there pretty much always is - the order they're defined in the
enum, or the numeric order. Alphabetic for strings isn't quite so
useful, although it would still make it easier to find a particular
value when looking over the code.

What makes you think that reordering affects performance though? Have
you measured it (in C#, not VB6)?
I wouldn't accidentally do it, because I'd be doing step over instead
of step into. However, I've gone into why you *would* want to use
properties earlier in the thread. If you've provided some validation
etc in the property setter, not performing that validation should be
the exception rather than the rule.


The problem is you can't always step over. If the code is

DoSomething(MyProp);

then you can't step over MyProp and into DoSomething (afaik).


I *think* there's a way you can avoid it, but I can't remember it.
Besides I always forget to step over until I'm in.


If you think you won't want to step into those properties in general, I
believe there's an attribute you can apply to stop the debugger from
doing it. I'm blowed if I can find the name of it though :(
<quote>
I find that by writing the faster code to start with I save work
optimising later, which is going to be a significant saving over a few
rare changes
</quote>


I've been programming in vb6 for many years and it's much easier in vb6 to
write incredibly inefficient code. For example IIf(x=1, 5 , 10) is 50 times
slower (I tested this once) than using an if statement because the first
returns a variant and the second just deals in ints. Vb6 is full of such
traps and it's very easy to write page after page of inefficient code so
I've become much more aware of such issues. I didn't realise until I had
this conversation just how much more efficient C# is (in some ways at
least). I could easily think of 50 examples in vb6 but struggled to find one
for C#. And the one I came up with wasn't very good :-) I good example in
vb6 was I found out at one stage that "If len(SomeString) = 0" was much
faster than "If SomeString = "" " so I started using len. The 2 methods were
practically identical so why not use the faster.


Well, using the Length property is minisculy faster in C#/.NET too -
but personally I would still use if (x=="") because I find that easier
to read. Others find the .Length property easier to read, so they use
that - it's fine.

One example of where people go wrong is when they want to optimise loop
iteration. There are three obvious ways of iterating through a list or
an array - say of strings:

#1:
int len = list.Count;
for (int i=0; i < len; i++)
{
string x = list[i];
}

#2:
for (int i=0; i < list.Count; i++)
{
string x = list[i];
}

#3:
foreach (string x in list)
{
}

Now, people will use #1 because they think it makes it faster to only
look at the Count property once. In fact, #2 is faster than #1 (I
believe) because the JIT is able to make use of that common pattern and
optimise away the bounds checks - at least in some situations. (It may
be for arrays but not lists - I honestly can't remember at the minute,
and it may well change between CLR versions.)

However, #3 is the simplest and most readable form, if you don't need
the index itself. It says everything which is required and *only* those
things which are required.

Is it the most efficient? Nope. How often is that going to matter
though? The difference in performance is absolutely miniscule, so much
so that you'd only notice it at all if you had a virtually empty loop
and were iterating through millions and millions of times. At that
point, *if* you discover that's a bottleneck, that's the right time to
change to the most efficient form (assuming you can then prove that the
change does actually help). Until then, use the simplest form.
That suggests that speed is the major contributor to your design
decisions, rather than maintainability. If that's not your actual
position, then we may well have less to argue about - but I hope you
can see how statements like the one above have led me to my belief.
Perhaps I should have taken more notice of your "two methods which are
practically the same" to start with.


Don't worry, I don't go out of my way and make really bad designs to make
minor optimisations.


But do you go out of your way to make tiny changes to the code which
take it away from the path of clearest readability, just for the sake
of performance which is probably insignificant? How would you go about
iterating through a list in your normal code?
Not necessarily. The difference may often be that the beginner's app
will be very quick - but not actually work properly. I'd hope that an
experienced coder would concentrate on getting something working and
maintainable, only worrying about the speed of individual sections when
those sections proved to be significantly.


Generally the beginners code is slower and more buggy (and took them up to
10 times longer to write it). If you find performance issues with a more
experienced coder's work it usually harder to optimise it.


Well, it's likely to be harder to optimise the architecture, but you
may well be able to optimise the code itself, simply because plenty of
people take the same attitude I do.
The areas of speed I take into account are ones of complexity - I will
try to avoid doing something O(n^2) instead of O(n) unless I know that
n will be very small. However, that is usually a case of design and
architecture rather than actual implementation, IME.


That makes sense, the more loops a piece of code is inside the more critical
things become.


Sort of. I wouldn't be worried between a readable implementation and a
less readable one that was a constant 10% faster. When the *complexity*
is different, that's a real problem - and can get very ugly very
quickly, even if a loop isn't executed very many times.

For instance, suppose in one situation you have a loop which is
executed a million times, with a linear complexity. Changing the
implementation so that each iteration takes 10% less time will only
save 10% of the total time.

Now suppose you have a loop which is executed just 100 times, but it
becomes worse for each iteration so that the overall complexity is
O(n^3). Finding a way of making it O(n) will probably save *much* more
than 10% on the total time, even though the loop is only executed 100
times instead of a million.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 23 '06 #44
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
What makes you think that reordering affects performance though? Have
you measured it (in C#, not VB6)?
It has to do a comparison to each value presumably starting at the top.
Putting a commonly used item towards the bottom should result in more
comparisons.
I *think* there's a way you can avoid it, but I can't remember it.
You could use the DebuggerStepThroughAttribute.
If you think you won't want to step into those properties in general, I
believe there's an attribute you can apply to stop the debugger from
doing it. I'm blowed if I can find the name of it though :(
It used to be applied to the designer generated code in InitializeComponent
I believe but doesn't look like it is anymore.
Well, using the Length property is minisculy faster in C#/.NET too -
but personally I would still use if (x=="") because I find that easier
to read. Others find the .Length property easier to read, so they use
that - it's fine.
I don't think there's much difference in readability myself so use the
faster.
Now, people will use #1 because they think it makes it faster to only
look at the Count property once. In fact, #2 is faster than #1 (I
believe) because the JIT is able to make use of that common pattern and
optimise away the bounds checks - at least in some situations. (It may
be for arrays but not lists - I honestly can't remember at the minute,
and it may well change between CLR versions.)
Interesting. I would have used #1 when I needed the index.
But do you go out of your way to make tiny changes to the code which
take it away from the path of clearest readability, just for the sake
of performance which is probably insignificant? How would you go about
iterating through a list in your normal code?


Generally I would use #3 but wouldn't think it was the end of the world if
#1 or #2 was used when #3 could have been. It's possible you are
"micro-optimising" readability if you are using things like (X=="") instead
of len because of readability. I wouldn't consider readability down to that
level.

Michael
Apr 24 '06 #45
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
#1:
int len = list.Count;
for (int i=0; i < len; i++)
{
string x = list[i];
}

#2:
for (int i=0; i < list.Count; i++)
{
string x = list[i];
}

#3:
foreach (string x in list)
{
}


Interesting, I done some testing and #3 was fastest (578ms), then #2 (469ms)
then #1 (406ms). The code I used is below.

Michael

private int[] _ints= new int[100000000];

private void button1_Click(object sender, System.EventArgs e)
{
int t = Environment.TickCount;
int count = _ints.Length;
for(int i = 0; i < count; i++)
{
_ints[i]++;
}
MessageBox.Show((Environment.TickCount - t).ToString());

t = Environment.TickCount;
for(int i = 0; i < _ints.Length; i++)
{
_ints[i]++;
}
MessageBox.Show((Environment.TickCount - t).ToString());

t = Environment.TickCount;
foreach(int i in _ints)
{
_ints[0] = i;
}
MessageBox.Show((Environment.TickCount - t).ToString());
}
Apr 24 '06 #46
"Michael C" <no****@nospam.com> wrote in message
news:el**************@TK2MSFTNGP04.phx.gbl...
Interesting, I done some testing and #3 was fastest (578ms), then #2
(469ms) then #1 (406ms). The code I used is below.


Oops, times were back to front, should be:
#1 578ms
#2 469ms
#3 406ms

Michael
Apr 24 '06 #47

"Brian Gideon" <br*********@yahoo.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
Jeffery Richter has an annotation in the Framework Design Guidelines
book in which he recommends the m_ prefix as well. He also metions
that s_ is good prefix for static variables. I haven't adopted it yet,
but I'm seriously considering it.

Mehdi wrote:
On Fri, 21 Apr 2006 16:12:44 -0400, Dave wrote:
> I'm never quite sure whether to use "this." or not when referring to
> fields
> or properties in the same class. It obviously works just fine without
> it
> but sometimes I wonder if using this. consistently may make the code
> easier
> to understand for someone else, etc. Using "this." makes it
> immediately
> clear, for example, that the variable being referred to is a member of
> the
> same class and is not declared in the method as a local variable.


If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight. When i
started coding in C#, i followed these conventions and hence always used
"this" in order to make it clear that i was accessing a member variable.

I then got tired of it and reverted to prefixing all my member variables
with "m_". It's ugly but at least it makes it immediately obvious to
anybody that a member variable is being involved and it removes the need
for the "this" (that you can far too easily forget to type).

Whether or not you're using "this" in your programs really depends on the
naming conventions you've chosen to follow.


It's a good idea to use both "this" and m_.

"this" gives you intellisense which elliminates typos and m_ makes it easier
to home in on your fields in the intellisense list.

Does anyone know if it is possible to make the form designer use a different
naming scheme for controls?
Apr 24 '06 #48
"Nick Hounsome" <Ne**@NickHounsome.Me.Uk> wrote in message
news:Kn********************@fe1.news.blueyonder.co .uk...
It's a good idea to use both "this" and m_.

"this" gives you intellisense which elliminates typos and m_ makes it
easier to home in on your fields in the intellisense list.


I don't see the point in using m and _. One or the other differentiates
module level variables just fine.

Michael
Apr 24 '06 #49

"Michael C" <no****@nospam.com> wrote in message
news:eY**************@TK2MSFTNGP04.phx.gbl...
"Nick Hounsome" <Ne**@NickHounsome.Me.Uk> wrote in message
news:Kn********************@fe1.news.blueyonder.co .uk...
It's a good idea to use both "this" and m_.

"this" gives you intellisense which elliminates typos and m_ makes it
easier to home in on your fields in the intellisense list.


I don't see the point in using m and _. One or the other differentiates
module level variables just fine.

Michael


If you don't use a prefix then your fields will be all mixed up with your
methods and properties and also the methods and properties of your bases and
interfaces in the intellisense list.

I often forget what I've called my fields, particularly when designing forms
where there is always a LOT of base stuff in the intellisense list.

I just type this.m_ and I have a shortlist of the stuff I actually care
about to pick from.
Apr 24 '06 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: flavourofbru | last post by:
Hi, I am stuck at a major part of the code in VC++. My algorithm is as follows: f_name = load(filename); //this also loads a text file. The text files contains numbers sepearted by tab....
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.