I know rule #1 of optimization is: don't do it! But I figured this was an easy question, and if I start using the faster method now I can save a lot of cpu time when I'm finished.
I'm making an RPG, and let's say this is part of a custom class:
public class Baddie{
int health;
int magic;
public Baddie(int health, int magic){
this.health = health;
this.magic = magic;
}
public int getHealth(){
return health;
}
Now, the answer to my question may be "there's no difference" and that's fine with me.. I just want to know. Is it quicker to get the Baddie's health using field access:
//Somewhere in the main thread, I get an instance of Baddie..
Baddie b = getScaryBadGuy();
int baddieHealth = b.health;
Or is it quicker to use a return method?
int baddieHealth = b.getHealth();
Copied and pasted from Designing for Performance:
Avoid Internal Getters/Setters
In native languages like C++ it's
common practice to use getters (e.g. i
= getCount()) instead of accessing the field directly (i = mCount). This is
an excellent habit for C++, because
the compiler can usually inline the
access, and if you need to restrict or
debug field access you can add the
code at any time.
On Android, this is a bad idea.
Virtual method calls are expensive,
much more so than instance field
lookups. It's reasonable to follow
common object-oriented programming
practices and have getters and setters
in the public interface, but within a
class you should always access fields
directly.
Without a JIT, direct field access is
about 3x faster than invoking a
trivial getter. With the JIT (where
direct field access is as cheap as
accessing a local), direct field
access is about 7x faster than
invoking a trivial getter. This is
true in Froyo, but will improve in the
future when the JIT inlines getter
methods.
Performance is always relative. It's usually better to think in terms of percentages or factors. If something takes a microsecond, maybe that's a lot, and maybe it's nothing. It depends on how many times per second you need to do it. That's the main reason premature optimization is frowned upon, it is done without knowing if there is a problem.
The compiler will optimize if it can. This is a perfect example of premature optimization. use whatever makes sense in your code. Don't worry about "saving cycles". The 2-3 cycles this may or may not save is outweighed by the millions of cycles it takes for any other operation.
IMO it's more a design question than optimization question. I would suggest not writing/generating any getter or setter until you actually need them to be accessed from outside of your class. This tends to keep coupling as low as possible.
Alternatively making those getters/setters private by default would have the same result but it's more code for no real benefit.
Related
why Google calls variables with the prefix "m" for example:
private int mSectionResourceId;
private int mTextResourceId;
I see it in all examples. But i not understand why they do it?
And now i have some example where it practic very good. If a called variabels without prefix i need write
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
this.sectionResourceId = sectionResourceId;
this.textResourceId = textResourceId;
but if i use prefix i can write
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
I think it more readable. Who can explain to me the pros and cons of a prefix?
The variables starting with m are telling you they are variables in the scope of your class. Member of the class.
Link to Android Code Style Guide
The m just stands for 'Member'. It is simply declared that your Variable is a Class-Member.
It is more readable Code, because you know where Class Members got declared, so you can find it pretty fast. You don't need to write this, even if you don't prefix your Variables with an m.
In your Example, this only makes it more readable when there is no prefix-m. Another developer knows that it is a instance variable (member variable) and so declared on top or bottom of the class.
It is a prefix for class member variables. It's just a naming convention.
Mostly sure, taken from Hungarian Notation where similar prefix: m_ stands for exactly the same).
Referring to pros & cons:
Pros:
it allows to type fewer chars during programming,
programmers that are used to use Hungarian Notation may found it easier to follow the code.
Cons:
as the code changes very often, it is easy to forget about changing prefixes every time, when variable changes it's purpose (especially during prototyping),
it makes the code starts to smell bad,
Generally, it is some kind of reinventing the wheel. Java has this keyword that should be more than enough for accessing proper variable. If it's not, the code requires refactoring, maybe because of naming glitches or using too wide variable scopes.
Personally, I do not recommend to use Hungarian Notation (even the part of Android Code Style). We have great IDEs that increases the readability of the code.
There is an exception. The code, where Hungarian Notation (or more general, specific code style) was already been used. It is a matter of consistency.
The m is just a member variable. A class member if you will. Useable with constructors like WebView M WebView then later on you would use something like mWebView.loadurl("example.com"); it's just a placeholder for the variable you created. You don't have to add the member class variable as an m but it's more organized if you do
i am new in android and java ... i am reading from couples of day about android parceling tutorial for transfer data or variables values from one activity to other or one class to other ... but i am not so understood about that.
can u tell me that is it necessary to use Parcelable for this purpose because same task can also be perform using static key word for variables as string,int or array type then why parcelable pls explain in detail ..
thanks for explanation in advance please provide comparison with example
While technically both approaches will work, there are a couple of flaws.
The first is that the static variable is static. If you have two instances of the same activity, they will both reference the same static object. This is probably not what you want.
Secondly, it's considered bad practice to access global variables. It makes it difficult to see what is going on, is difficult to test and you someone (another class) can modify your data. This creates some horrendous bugs.
By passing the data via a Parcelable object it is very clear what you are doing and you avoid both of these problems.
Note that this advice is not specific to Android, rather to Java and programming in general.
Static references never get garbage collected so you end up creating something called a memory leak.
You are keeping an object in memory that you don't need and it can't be freed up.
If you instantiate enough objects like this you will get an out of memory (oom) exception which will cause the app to crash.
I've started to really like using C# and Java enums in my code for several reasons:
They are much more type-safe than integers, strings, or sets of boolean flags.
They lead to more readable code.
It's more difficult to set an enum to an invalid value than an int or string.
They make it easy to discover the allowed values for a variable or parameter.
Everything I've read indicates that they perform just as well as integers in C# and most JVMs.
However, the Android framework has numerous cases where flags of various types need to be passed around, but none of them seem to use enums. A couple of examples where I would think their use would be beneficial are Toast.LENGTH_SHORT / Toast.LENGTH_LONG and View.GONE, View.VISIBLE, etc.
Why is this? Do enums perform worse than simple integer values in Dalvik? Is there some other drawback I'm not aware of?
This answer is out of date as of March 2011.
Enums can be used on Froyo and up - according to this answer (Why was “Avoid Enums Where You Only Need Ints” removed from Android's performance tips?) from a member of the Android VM team (and his blog).
Previous Answer:
The official Android team recommendation is to avoid enums whenever you can avoid it:
Enums are very convenient, but
unfortunately can be painful when size
and speed matter. For example, this:
public enum Shrubbery { GROUND, CRAWLING, HANGING }
adds 740 bytes to
your .dex file compared to the
equivalent class with three public
static final ints. On first use, the
class initializer invokes the
method on objects representing each of
the enumerated values. Each object
gets its own static field, and the
full set is stored in an array (a
static field called "$VALUES"). That's
a lot of code and data, just for three
integers. Additionally, this:
Shrubbery shrub = Shrubbery.GROUND;
causes a static field lookup. If
"GROUND" were a static final int, the
compiler would treat it as a known
constant and inline it.
Source: Avoid Enums Where You Only Need Ints
Integers are smaller, and require less overhead, something that still matters on mobile devices.
A colleague of mine performed a small test regarding this situation. He auto generated a
class and an enum with the same amount of "enums". I believe he generated 30000 entries.
The results were:
.class for the class was roughly 1200KB
.class for the enum was roughly 800KB
Hope this helps someone.
In the source code of Activity.java, I see some methods bellow :
public View findViewById(int id) {
return getWindow().findViewById(id);
}
and the definition of getWindow method:
public Window getWindow() {
return mWindow;
}
But as the following rules:
Avoid Internal Getters/Setters
In native languages like C++ it's
common practice to use getters (e.g. i
= getCount()) instead of accessing the field directly (i = mCount). This is
an excellent habit for C++, because
the compiler can usually inline the
access, and if you need to restrict or
debug field access you can add the
code at any time.
On Android, this is a bad idea.
Virtual method calls are expensive,
much more so than instance field
lookups. It's reasonable to follow
common object-oriented programming
practices and have getters and setters
in the public interface, but within a
class you should always access fields
directly.
Without a JIT, direct field access is
about 3x faster than invoking a
trivial getter. With the JIT (where
direct field access is as cheap as
accessing a local), direct field
access is about 7x faster than
invoking a trivial getter. This is
true in Froyo, but will improve in the
future when the JIT inlines getter
methods.
so I want to know why android developers not access this mWindow object directly? If the JIT of the current android versions cannot inline the access, getWindow().findViewById(id) will costs more time than mWindow.findViewById(id), and findViewById is a rather frequently used method.
First: you can't access it because it's private.
Why is it private?
As you said, accessing members directly is faster. On the other hand, you are invoking a method that isn't very fast as it will lookup for some view in the view hierarchy. So using a method instead of a direct access will incur in a small overhead in terms of percentage of the total time that it would take to perform that task.
Anyway, I believe that the reason for this is encapsulation.
You are invoking something you don't own (that is the Android SDK). So, you shouldn't make any assumptions of whats happening "in the other side". Simply use this method and expect that it will return the view you want (or null if it doesn't exists).
Maybe the next version of android will use a different method to lookup a view, not calling getWindow(). If you use this method, they (Google/Android) can simply mark the method as deprecated and "forward" your invocation to the newest implementation. If you were calling directly getWindow(), maybe you would be looking for something that is no longer placed in there.
You can't access the mWindow property directly - it's private.
And I wouldn't care about the speed of findViewById, since you only need to call it once for every view in your layout in your onCreate() method and store the views in members of your activity. You do call findViewById only once per view, don't you? ;-)
However, if you really care about these things, you could call getWindow() for yourself, store it into a local variable and call findViewById on it directly. I wouldn't recommend this because all your performance increasements here are not worth the time and anyway will be obsolete with future versions of the JIT.
If you do this I would be very interested in the amount of microseconds you saved. :-)
We have a reason to smile now...
The android documentation which says to avoid internal getters and setters will change soon, supposedly progruard was added to Gingerbread platform which does a fine job of inlining accessor's, please refer to "Avoid Internal Getters/Setters" is bad advice and these two SO posts.
https://stackoverflow.com/a/6716573/892055
https://stackoverflow.com/a/4930538/892055
Just a random question. I'm learning a bit of Android right now, and in most examples, it seems a lot of common items (such as buttons, editboxes etc) get requested within each function using (cast) findViewById().
Is it considered good or bad practice to store the result of that in an Activity's member values? Simple example:
public class MyActivity extends Activity {
private EditText myText;
public void onCreate(blah blah) {
// blah
this.myText = (EditText) findViewById(R.id.mytext);
}
}
and use the myText field from there on. I think it'd be good for performance (depending on findViewById's inner workings, I'm quite sure it's already very fast), but I haven't seen it be encouraged yet. Also, it wouldn't be the first time I encountered a situation where 'caching' something like this leads to problems (had a case where database connections weren't released properly because I remembered a ConnectionManager or something in that fashion).
Secondly, somewhat related, if you want to remember something across methods in your Activity (and later on too, when the Activity is restarted later), is it wiser to keep up both a class field and a value in SharedPreferences, or would calling SharedPreferences each time for setting / getting the value where it's needing be a better solution? (better being 'cleaner, without impacting performance significantly)
That is completely normal practice and is exactly what you SHOULD be doing. If you're worried about memory leaks, or holding references or whatever, don't be concerned about that when dealing with views.
However, you SHOULD be careful about holding references to other contexts because that COULD cause a memory leak. That doesn't mean you shouldn't do it, just be careful about when you're doing it.
is it wiser to keep up both a class field and a value in SharedPreferences, or would calling SharedPreferences each time for setting / getting the value where it's needing be a better solution?
You should do both. You should keep a member variable for when you only need to read the data, just be sure that when you WRITE to the member variable, you also change the shared preference.
Also, it wouldn't be the first time I encountered a situation where 'caching' something like this leads to problems (had a case where database connections weren't released properly because I remembered a ConnectionManager or something in that fashion).
This is what I was saying first. It all depends on what you're storing. Views are fine to store, contexts can be dangerous, and database connections and registered listeners can cause really weird bugs. It all depends on the specific case.