I have a doubt which will be better - using getter, setter methods or direct field access ?
In android site Performance Tips - its given as "Avoid Internal Getters/Setters".
My choice is to use direct field access, but my friends are telling to use getter setter methods in Android. Is that right if so then what is the use of using getter setter methods? How the performance will be improved?
To add to the answer from Ed, what the link you send refers to is to avoid internal getter/setter. Within the same class, using the getter/setter to access a field will cost you for nothing...
Does not mean you should not use getter/setter from other classes. The cost you may pay in performance is worth it in maintainability and code design / structure.
The choice between using getters and setters and allowing for direct field access is not typically one of performance, but instead one of maintainability and encapsulation of data. Typically you will use getters and setters to have tighter control over your data.
Unless you are running in a tight loop that needs to go as fast as the hardware will allow it and the function call is actually proven to be cosnuming a relatively significant amount of CPU time you don't have to worry about the performance.
How to Improve app performance
Performance is most important for user fulfillment
Some technique to improve app performance
1) Avoid Unnecessary variables and package
create only needed variables and import used package remove unused package
2) Create Setter getter to store and access data
3) Replace array to List or any java collection
4) Data reuse
Related
I'm looking a way to improve the mapping mechanisms between the model classes from the different layers in my App.
I've model classes, the ones that I use in my App, in the business logic layer such as a Presenter. For example a User class.
I've server-side entities, these are the ones that I use to deserialize the responses from the server-side endpoints, through Retrofit or any other technology. These ones usually contain the Gson annotations for the fields. For example a ApiUserResponse class.
And I've DTO entities, these are the ones that represent a DB table in my App. I'm using Realm right now, but I've worked with ORMlite and Room. These types of classes also contain DB related annotations. For example a UserDTO class.
My cache repositories (the ones that fetch data from the DB) and my network repositories (the ones that fetch data from the server-side) both expose RxJava methods, returning the responses wrapped in Observable classes.
What I'm doing right now to parse the DTO entities and the server-side entities is add an extended function to the Observable class which receives a functions as argument. And that's the mechanism that I'm using to parse the DTOs and server-side entities into model classes. For example:
myLoginRepository.getUser("someId")
.mapTo(::myMappingFunction)
...
fun myMappingFunction(userResponse: ApiUserResponse): User {
return User(userResponse.id, userResponse.name, userResponse.lastname)
}
Internally the only thing that the mapTo extended function does is using a flatMap to flat the Observable stream and using a map to parse the collection.
I think that this is a pretty good way to implement the mapping between model-related classes, but I'm looking a way to improve it or do something completely different but that require less coding. Obviously this example is pretty straight forward, but currently I'm having a Mappings.kt file which is growing like crazy with each new mapping function.
Any suggestion?
Maybe http://modelmapper.org/ is something for you. This way you can spare your own mapping functions and you can even specify some sophisticated mapping functions. However it may cost you something in regards to performance (looks like reflection access all the way?).
Note: I didn't use the library myself yet, but it looks promising enough to recommend it. In the last project I helped out, they built their own modelmapper which probably wasn't such a good idea (lots of corner cases forgotten, which then led to strange behaviour later on or manually mapped the wrong fields; however your variant can suffer from that too).
Just found another article regarding mapping frameworks and their performance:
http://www.baeldung.com/java-performance-mapping-frameworks doesn't look that good for ModelMapper
You may also just want to generate your mapping functions. Similar to what you have now. Or just use a live template for it?
Manually writing your mappings may sooner or later introduce mistakes you are not identifying that easily anymore, except you test them all accordingly. Which you do, right? ;-)
You can convert your DTO object to entity or vice versa with converter.
Converter
ConversionService
You can implement Converter interface,It is a functional interface and you must implement convert method, then convert your DTO to entity, Where you want to convert them, just you should inject ConversionService and use convert method.
You should only have one class that representes both the entities and the model class from the network
If you want to use Room database and Retrofit for Api calls you should use like this
#Entity("tableName = something")
data class Something{
#SerializedName("name")
val name : String,
#SerializedName("number")
val number : Int}
I am writing an Android game in Kotlin where the board changes according to a specific pattern - which pattern, depends on the level the user currently plays.
I need a way to use many different patterns (20, 30 at max) in my code, deciding which one of them to use at runtime.
I thought of encoding each pattern as a string, putting all these strings in a file and at runtime loading it and parsing the desired one. However, the patterns aren't so simple, so parsing will be a complicated process. It also seems as an over-complication.
My best idea right now is writing a class for each distinct pattern (and a common parent abstract class to be used by the calling entities). Each class will have a single "apply" method that applies that specific pattern on the board.
However, it means dozens of classes (I could put them in a different folder so they don't make the main code folder too crowded), and a big switch case which maps the pattern id (received from the level manager) to the specific implementation. I'm pretty sure I don't want that.
Any better ideas? Thanks in advance.
It depends on what may happen in future. Will there be more patterns? Are they have parts which are common? Will there be other rules, say if you have used pattern 1 then you cannot go to pattern 1 again next time and so on?
Either way you will have a dozen of patterns. Storing them as a string, object, file, model or whatever is totally up to you but you will not escape from having them. What i mean here is having 1 file with 20 patterns is not very different from having 20 files each with 1 pattern. So no, having many classes is not something that is wrong in that case.
Put them in a folder and create a facade. That way all you need to do to use them is call the facade and get apply method based on some criteria(pattern id):
The facade itself can either map id to behavior or directly checks if there is file(class) named that way in the folder. If there is one it will get instance of it and call apply method on it as a result. You can store the instance so:
pros:
can be changed at any moment and behavior will change
there will be only 1 way to present pattern ( no option to get 2 patterns trying to draw them self's )
cons:
if some patterns at some point need to have one more method you need to change all of the classes and the facade
That way you don't need switch and there is no need to change the facade itself if new pattern shows up - just create new file with its own implementation and you are ready to go.
The question is not that ideal for SO, however, I found it really interesting. Hence I am putting some of my ideas if I had to design such game.
This is a level based game which incurs different board patterns in different levels. So it is really important that how you are designing your patterns to be translated into the board. Your pattern may have some generic keywords which can be translated into a program to create a board part by part. Let us look into an example, for making the idea clearer.
Suppose, you are building a line of pipes. Each part is being connected with the already constructed pipe. There can be a lot of differently shaped pipes in your hand. So while building a pattern, you just name each shape. For example, left-round-vertical-up, right-round-vertical-up, straight-horizontal, straight-vertical etc. You have a Factory class which knows the implementation of each of your shape. Now its pretty simple to store the whole pattern in your local database table. Which will be translated into your board in runtime, based on the logic your Factory class has.
A sample row in your database table may look like the following.
id level_number level_passed pattern_desc
-- ------------ ------------ ------------
1 1 1 left-round-vertical-up, straight-horizontal, straight-vertical, right-round-vertical-up
2 1 0 straight-horizontal, straight-vertical, right-round-vertical-up
So when you have the data in the structure above in your database and you know all the keywords of your pipe segments to be translated in your board, its simpler for you to maintain the code and to add new patterns via API call.
In your current structure, its difficult to update your patterns without any application update. However, in the proposed architecture, you can easily add new patterns in different levels using a simple API call from your server. The application knows how to parse the pattern and can show them accordingly. Then your job is to call an API to get the newly introduced patterns from your server and insert them into your table for storing patterns with appropriate values.
The factory implementation might require many classes, which indicates each shape of your pipe segment. However, you are not writing classes for each of your patterns which is quite a lot and difficult to manage further.
Hope that helps!
I have an arraylist in the Constants file. Is there a chance that same arraylist has different values in different classes at the same time?
May be the accessing of arraylist happens in different threads also. If it happens so what can I do to fix this? The arraylist does gets modified based on a call back method from Firebase.
NB :- I don't have any code to post here.
That's not limited to List's. In every concurrent environment you have to take precautions that there is no race condition or unforeseen mutation. To solve this there are several implementations in the java.util.concurrent package. Here is an overview
There is also the option to use the java tools for concurrency e.g. synchronization, atomic fields, lock objects etc. etc.
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
I have an application that requires data from a list in more than one classes extending Context. Sometimes I can pass the reference of the list to these classes and sometimes I cannot. So, I was wondering if putting the list to R.array.mylist and then continually calling from them in different classes might be a better idea? I specifically want to know if there is "high/low/acceptable"(in terms of memory & CPU) overhead to calling Resources continually.
Any suggestions/answers is appreciated. Thank you.
The "R" (resources) file is a static reference to XML defined objects. Creating a reference in XML allows you to reference those objects using objects that extend Context. It uses the Resources class to reference these objects.
If you inspect the source code (http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/res/Resources.java#Resources) you will see it is essentially a handler for these XML defined classes. If you have access to Context then there are few steps you can take to improve upon a the short reference path that Context and Resources provide.
You can build your own mechanism for storing and/or referencing this array or you can use the one provided for you by the framework. Most likely you will find that the framework offers acceptable performance in terms of speed, memory allocation, etc. Since Context and Resources are loaded with your Application object, there is little overhead involved in using these tools. You will notice the source code attempts to optimize caching of XML objects, etc. That means the accessing and caching mechanism may not be optimized for some use-cases.
You may have situations where you can beat the effectiveness of the framework, but for most situations it is just fine. If you have a special use-case (like an array of 100,000 elements) then you might be able to optimize better than the framework. Most likely you will find that it is both convenient and effective to store your array as an XML defined object.
I want to save my Android game state so the user can pick up and play from where he/she left off.
I have been reading about the serializable interface, but have some questions.
Aside from background rendering and a few other things my game is performed from one class.
Let me explain what that means. I have a class A, and all the different elements of the game are stored in various arraylists and such, in A. SO I have dozens of instances of classes B,C,D,E... all being called and updated (when the screen updates) from class A.
My problem is I am unsure what needs to be serializable. Every class B,C,D.. (i.e. every class? or just A? I don't see why serializing A and then saving the output in SQLite DB wouldnt store all the data.
Just as a suggestion, you may also want to look at Berkeley DB Java Edition, specifically at the DPL (Data Persistence Layer) API. Like SQLite, it's a transactionally protected, recoverable, fast, small footprint database library. However, the DPL allows you to directly persist your classes, making it a much easier choice for Java application developers.
Here's a technical white paper describing the API and how to use it.
if you want to serialize some object. then look at this link use other object in place of hashmmap object that has been specified in this link.