I just read a pretty interesting article on how android (and i assume other OSs) work when low on memory. How is this done theoretically? Is it similar to Java's object serialization?
In a word: yes.
In a few more words, sort of. You have to handle more of it manually than personally I'd like. Essentially, all Android provides for you is a hash to shove a few serializable objects, referenced by strings, that is guaranteed to be safe across application shutdowns. So, whenever something happens that you'd like to preserve across a shutdown of your application, you are responsible for updating this saved state hash (and letting Android know that you've done so). This includes things like half-finished text entry in form fields. That means you have a lot to listen to.
Android will then call a particular hook in your Activity that handles restoring state to the Activity when it recycles your application and you need to do so. This doesn't happen for all recycles — there are various states of being/existence for your application.
The screwy part is that because you're expected to do this sort of tedious work anyway, Android gets lazy and implements things like screen rotation as a full recycle of your application.
I'm making it sound worse than it really is once you get used to it; it's really not a bad way of solving the problem in the confines of Java and mobile computing.
Of course, this is a response regarding Android. Other (desktop) OS's rely on Virtual Memory and Paging to deal with memory constraints.
Related
How can I control life cycle of QML forms (I mean windows)? I am talking about onCreate, onResume, onPause etc. methods on Android or life cycle of views on iOS. And Can I work this life cycle of QML forms on Android, iOS, Windows 10 Mobile, desktop etc.?
Design of Qt Quick (QML) applications is different from Android ones. There is no difference between views and objects like Button, Text, etc. Every QML object with graphical representation inherits Item and it is possible to define Component.onCompleted and Component.onDestruction functions. They will be executed once object is created and destroyed. If you also need a pause signal I suggest creating functions pause() and resume() in every view you create and create an object that will manage the views - create, destroy, pause and resume them.
Please notice that you need to take care of transitions between views and states yourself. Also as you can create your own QML objects it is worth considering creating a template of a view and then only inherit it.
This will work with every system you deploy the app on.
If you have more questions, need example etc. consider editing the question or leaving a comment.
I want to thank BaCaRoZzo once again for useful tips. I added them to this answer.
I have created an example project that tries to mimic Android app life cycle. This will work with every OS. This is just an example but I think that similar approach may be used in release source. However, first you need to understand the nature of the QML. This is high level language that is already being managed by some other process. It is far different from Java. For example take a look at the fragment of the docs about a state used by background processes:
A Qt Quick application should not usually handle this state at the QML
level. Instead, you should unload the entire UI and reload the QML
files whenever the application becomes active again.
So if I were you I would only save sensitive data when I detect application is going to background. No need to try and unlod views etc. It would be needless uphill struggle becuase QML is not designed for this. Instead let your app be killed if OS needs more memory.
You can find the example project here. You can use it if you want. It contains comments to let you better understand what is going on.
Yesterday, I spent 12 hours becoming a student of Traceview. I didn't even know it existed (hangs head in shame) previous to this.
Now that I've overcome the absolute shock of the data it produces, I find Traceview can be boiled down into a couple simple concepts:
Sort by "EXCL CPU TIME" to determine exactly how much usage each individual method is using in isolation.
Look at the frequency of calls and the cpu time/real time per call. Obviously higher calls should be looked into. In most of my experience, if you sort by #1 above, methods which are called too much and take too much time will also be at the top of the list (makes sense as they are also using the most CPU).
Anyway, doing these two steps above I find 3-4 methods which are always using 90% of my CPU and taking up most of the real time delays in my app. The only problem is, none of these methods are methods I wrote, they are system methods such as:
BitmapFactory methods
WebKit methods
And other system methods
This being said, is it a correct to assume that if the top resource hogs are system methods, then it must have something to do with my design of my layouts? I am at a loss as to how BitmapFactory could be so high, my layouts aren't extremely complicated, though in one Activity BitmapFactory is taking 95% of resources itself.
TL;DR - If I run a Traceview, and if I find the top hogs of resources are all system methods, does this mean it's a layout issue? Or, how else can I tell why the system method is so high as it doesn't relate directly to my custom methods.
Thank you very much,
Ryan
I find Traceview can be boiled down into a couple simple concepts:
Those concepts are not the best, IMHO.
Sort by "EXCL CPU TIME" to determine exactly how much usage each individual method is using in isolation
In particular, this concept is fairly lousy IMHO. Yes, this is useful data. However, you then need to work back up the call stack to try to figure out what is triggering this. Sometimes, it will directly be your code. Sometimes, it will be something else that you recognize that is part of the framework (e.g., onDraw() of a View). Just knowing that some random method is taking up a bunch of time does you no good until you identify what is triggering that method to be invoked in the first place.
If I run a Traceview, and if I find the top hogs of resources are all system methods, does this mean it's a layout issue?
No.
Or, how else can I tell why the system method is so high as it doesn't relate directly to my custom methods.
Work your way up the call stack to figure out who is calling these methods so frequently, or at inopportune times.
For example, in the BitmapFactory example, you will probably find that you (or a library that you are using) is calling BitmapFactory, and perhaps is doing so on the main application thread.
To work your way up the call stack, click the triangle on the left edge of the row representing some method of interest. You will then see two branches beneath that: "Parents" and "Children". The "Parents" represent the next level up the call stack from the method, and you can continue working your way up the chain of parents until you find something that you recognize.
That's why, IMHO, you are better served sorting by inclusive time, as your code (where it directly is the culprit) will tend to bubble towards the top.
Well, I found the problem and it's bitter sweet. It's sweet because it wasn't my code nor layout causing the problem, it was the admob AdView using the loadAdOnCreate="true" to create ads. It's bitter, because I now may have to switch sources of revenue if I can't remove the loading delay created by the AdView! That was a tough one to find, I should have anticipated this though!
I am going through a bit of a design dilemma, I have been targeting Android 2.3.3 and have a custom implementation of a ContentProvider. I then have a class of static methods to abstract the Content provider - providing me with objects representing each entity (row) based upon my query. For a while I was very comfortable with working like this, until I started wanting to use the whole collection in a number of places, for performing "hit tests" and drawing to the screen. I then had the headache of keeping my object representations up to date, and at this point have decided I need to step back and reconsider where to take this.
As I say, I am presently using 2.3.3, and realise that in 3.0 CursorLoader overcomes a lot of the problems I have encountered. I still need to support smart phones though, so unless there will be a backport I cannot do this.
As an interim solution I started to register notifyChange listeners so that I can rebuild a collection with my original query, but this strikes me as very CPU intensive and potentially slow. I haven't yet decided whether I should roll back from using my static facade and instead use the now obsolete managedQuery call from Activity.
I therefore have two questions:
1) Is there a preferrable way to avoid the issues with working against a collection based around a contentProvider?
2) Have you any advice on working with raw cursors in an activity? Should I be making objects out of them or working with the cursor as-is? I certainly feel they should be in an AsynTask while performing the query, but after that can I use them anywhere?
Ok, well I came to a decision and it works reliably.
1) Is there a preferable way to avoid
the issues with working against a
collection based around a
ContentProvider?
I have decided that the approach I took was correct; In my situation it is preferred to make a cache rather than maintain a cursor (managed or not) to the ContentProvider; this allows me to reuse methods and reduce the amount of code that requires testing. NotifyChange listeners are important until working on 3.0+ and that means I should guarantee the NotifyChange is called - another argument for centralising all of this code, so that it indeed triggers the changes when expected.
2) Have you any advice on working with
raw cursors in an activity? Should I
be making objects out of them or
working with the cursor as-is? I
certainly feel they should be in an
AsyncTask while performing the query,
but after that can I use them
anywhere?
In my use case I have decided it is a matter of thinking about what it is I am planning to create - avoid unnecessary work, with respect to returning unnecessary rows & fields and potentially creating unnecessary objects. If I am looking to create a map of entry names and entry IDs then I shouldn't be getting all of the other fields too. Abstracting from the collection is good but it must be lightweight and take in to account how the data is used - whether it is a one-off or may be used repeatedly. It is important that it is written for performance rather than completeness.
I read many times that reflection will slow down the phone performance.
How true is this?
For example in my case, I get some parameters from a web service which have the same name as the parameters of a class I have in my android app. so I just set the values of these parameters using java fields and reflection... it doesn't seem to slow down the performance..
can anybody explain to me the fact behind this idea about reflection slowing down performance?
Take a look at this question. Basically, you are getting outside of the optimizations that the compiler can perform because reflection happens dynamically.
If you're not making a lot of reflection calls (e.g., it would be bad to do inside the getView of a ListView), you can probably get away with it. It's there to be used, just be judicious about it.
how true is this?
It is slower than not using reflection. It is definitely something you want to avoid in loops or during rapid UI processing (e.g., scrolling a ListView).
i get some parameters from a web service which have the same name as the parameters of a class i have in my android app. so i just set the values of these parameters using java fields and reflection... it doesn't seem to slow down the performance..
It does, though it may not be noticeable to the user in this case.
can anybody explain to me the fact behind this idea about reflection slowing down performance?
See the link provided by #Brian Cooley in his answer. Bear in mind that reflection on Dalvik (the virtual machine in Android) may be slower than reflection on the Java VM -- I am really rather certain it is not faster, at any rate.
I am a complete noob to android but I have been programing c# for a long time. I am writing an android application and have gotten to a point where the c# programmer in me wants to start creating a loosely coupled design and and moving code into different layers, using interfaces, etc.
But then I stumble upon the Designing for performance guidelines it is telling me to avoid object creation and then it also is saying to optimize judicially.
Do I just build based on good design and then deal with performance issues as they come up?
The last thing I want to do is go through the work of building a application and have it perform poorly. Can someone point me to some examples of application that are designed well and have good performance or just make some recommendations?
Thanks
I've found AndEngine to be fairly well designed and it has to be concerned with performance since it is a game development library -- so you might pull down a copy of it and read the source.
In the "Designing for performance" document, I would point out this statement:
Note that although this document
primarily covers micro-optimizations,
these will almost never make or break
your software. Choosing the right
algorithms and data structures should
always be your priority, but is
outside the scope of this document.
An example of this would be creating a particle system. A good way to model it is to have a ParticleSystem object that holds a collection of Particle objects...maybe those Particles implement a Particle interface...this is not the place to avoid object creation. However, for performance reasons, you will want to optimize the ParticleSystem to recycle Particle objects rather than creating them from scratch every time you spawn one.
Personally, I haven't found performance to be much of a limiting factor but I suppose that will really depend on what type of app you're building.
My opinion is to build a suitable design first, test the performance, and optimize from there.
Pay more attention to Donald Knuth's quote that appear in the same article:
"We should forget about small
efficiencies, say about 97% of the
time: premature optimization is the
root of all evil.root of all evil."
Then if you are dealing with the other 3% you'll see...
As a general rule, the thing to do is keep the data structure as simple and normalized as you can. Like don't just throw in hash table data structures just because they are easy to grab. Know how to do profiling (here's my method) and if you have a real performance problem then fix it. Otherwise, the simpler the better, even if that means simple arrays, lists, and O(N) loops.
The reason to keep the data structure normalized is, if it is not, then it can have inconsistent states, and you will have a strong temptation to write notification-style code to try to keep it consistent. Those can be real performance killers. If you do those, the profiling will tell you it that's what is happening.
If you must have redundant data, I think it's better to be able to tolerate some temporary inconsistency, that you periodically repair by passing through the data. This is better than trying to intensely guarantee consistency at all times by notifications.
Another problem with unnormalized data structure is it can have lots of object creation and destruction. That also can be a real performance killer, although you can ameliorate it with the pool technique.