The this keyword is optional when accessing instance fields, properties, and methods in languages like C# and Java.
I’ve been doing some best practice research on various languages lately, and have noticed many places recommend creating a local reference to instance fields within methods because it’s more efficient. The latest mention was in an Android tutorial.
It seems to me that if you specify this._obj, it should be just as efficient as a local variable. Is this correct or is it just as ‘costly’ as not using this?
Does the answer change from the Android Dalvik VM, to standard Java, to C#?
public class test {
private Object[] _obj;
protected void myMethod() {
Object[] obj = _obj;
// Is there an appreciable differnce between
for(int i = 0; i < obj.length; i++) {
// do stuff
}
// and this?
for(int i = 0; i < this._obj.length; i++) {
// do stuff
}
}
}
No, there is absolutely no change in efficiency. Remember that in many languages, several equivalent expressions will reduce down to identical statements in the underlying bytecode or assembly or whatever the higher level language translates into.
The answer is uniform across the languages and VMs you mention.
Use it when necessary, like when a method parameter has the same name as an instance variable.
Unless CPU cycles (or memory, etc.) are a top priority, value clarity above less expressive but more efficient language syntax.