If you are going to access a variable a few or more times in a method, this
is a very good technique to get in the habit of.  I'm not sure I see how it
impacts readability and maintainability that match -- on the contrary, I
think it can help, since you are documenting that the variable will serve as
a constant during the function (as a bonus, declare the local variable as a
final to have the compiler enforce this).

When accessing a member variable, the compiler will very often need to
dereference 'this' and reload the value from memory each time it is access,
since the value could have changed since it was last used.  Accessing a
local variable in contrast can be done just by using the existing value in a
register.

On Mon, Jan 5, 2009 at 3:44 PM, Dave Kong <davek...@gmail.com> wrote:

> In the Notepad Exercise 2, there is a section about perf (see excerpt)
>
> *Note:* We assign the mNotesCursor field to a local variable at the start
> of the method. This is done as an optimization of the Android code.
> Accessing a local variable is much more efficient than accessing a field in
> the Dalvik VM, so by doing this we make only one access to the field, and
> five accesses to the local variable, making the routine much more efficient.
> It is recommended that you use this optimization when possible.
>
> Can someone tell me in a bit more precise terms how "much more efficient"
> is to use a local variable? I'm trying to weigh the perf benefit vs. code
> readability/maintainability. It is a pain to reassign n fields to n local
> variables for m methods...
>
> Thanks!
>
> -dave
>
> >
>


-- 
Dianne Hackborn
Android framework engineer
hack...@android.com

Note: please don't send private questions to me, as I don't have time to
provide private support.  All such questions should be posted on public
forums, where I and others can see and answer them.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers-unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to