HashMaps fast enough? - java

Im building my own little Opengl Library based on Lwjgl. In the moment im using HashMaps for storing things like render objects, scens or shader programs, because i want to have on Class the user can see, and there create methods to modify, create, i dont know... other objects or classes which are protected.
So, to explain this:
There is a class called "ShaderProgram". But instead to allow the user to create one, with ShaderProgram s = new ShaderProgram(...); , i create a method in my "main class", called "createShaderProgram", give it the params, create a shader program and put it to the hashMap called shaderPrograms, with a name the user decides. for example with MyClass.createShaderProgram("particle_shader", ...) i can create a shader for my particles, and then with MyClass.binShaderProgram("particle_shader") or something like this, i can use it.
BUT: Is this fast enough? Or are there other reasons to change it to int indicies, or, completely allow the user to use all the classes? Because for example im creating the render objects like this, too, and in each frame to do MyClass.getRenderObject("ACube").move(...) ... can i do this? What do you think about this?

Access complexity time for hash table is O(n) in the worst case:
Time Complexity of HashMap methods
So Yes, I would say that if performance accessing your objects collections is so important you should use 1:1 indexed collections like arrays.

Related

How to organize configuration values in java project

Let's say I'm programming a small RPG game. I have several instances of the Enemy class. They share common properties (they all have a name, an amount of life/strength/dexterity/a weapon, etc), but all these values are different for each enemy. I'm looking for an appropriate way to initiate these instances.
I'm new to programming and Java, so I'm looking for the best practice to properly organize information in my project.
My first idea was, when creating the instance of the game, to instantiate all the occurrences of the required enemies in the constructor of the Game object, and put everything in a vector. Something like Enemy e1 = new Enemy("goblin", 10, 14, 10, a_weapon, ...). But this can get very tedious if there are a lot of enemies, a lot of properties, it gets very hard to maintain, and I don't find very "logical" to put that in the constructor of the Game object.
I just discovered XML files, and it looks promising. So maybe I could put everything in an XML file, and parse it in my program to extract the data and create all the enemies from it. It could look like
<Enemies>
<Enemy>
<Name>"Goblin"</Name>
<Strength>20</Strength>
<Agility>20</Agility>
<Life>20</Life>
<Weapon>
<Name>"Sword"</Name>
<Damage>3</Damage>
</Weapon>
<Enemy>
<Enemy>
...
</Enemy>
</Enemies>
I guess I could write a function that parses the XML file, extract the data and create the vector of enemies automatically, so I just have to edit the XML file to modify the values.
However, and before I dig into this solution, I want to ask if this is the preferred method, and if not, what would be the most common way of managing this kind of situation.

Most efficient practice to access objects in other classes: Java

I am currently creating a dungeon crawler. I handle all of the dungeon generation, collision box generation, treasures and enemy generation, and player generation in one class called Dungeon. Each of the objects created in the dungeon class has a getter.
In the Main class, I am using an animation timer to handle all of the updates from the player moving, opening treasures, etc. This requires access to many of the objects created in the Dungeon class.
I am trying to better understand the use and benefit of object references in Java. My question is: What is the more efficient method to access the variables in the Dungeon class (or any other class for that matter) since I am accessing them hundreds or thousands of times?
For example, all of the treasures in the dungeon are in an ArrayList variable that is a member variable of the Dungeon class. So, I can retrieve that array list in my Main class like this: dungeon.getTreasureList(). If I need to get a specific item in that ArrayList I could use: dungeon.getTreasureList().get(i) where i is the index of the treasure object I want. This is fine for short calls (organizationally speaking) but it gets really messy with longer calls like so: dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls())
Alternatively, I could create a reference to the treasureList in my Main like this: ArrayList<Treasure> treasure = dungeon.getTreasureList(). Then, if I need a specific object in the ArrayList I can call: treasure.get(i). This can clean up the long call above to something more like this: player.topIntersects(collisions.getWalls());. This is much easier to read and, as a result, I favor this method a bit more.
Disregarding the organizational benefits, is it a better practice to create a reference to access a variable to access information, or use the longer form and getters (like thisdungeon.getTreasureList().get(i))?
It would seem, that by creating a reference for player and collisions in the call dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls()) I am saving two function calls by using player.topIntersects(collisions.getWalls());. Namely, one function call to dungeon.getPlayer()and one call to dungeon.getCollisions().
Since this is being called thousands of times while the game is running, it seems safe to assume I am saving many thousand function calls to dungeon.getPlayer()and dungeon.getCollisions(), resulting in a more efficient code. Am I right in this assumption?
EDIT: Trying to make the question more objective and less opinion based and corrected misleading phrasing
My opinion is that this question will be closed soon, because it's too opinion-based.
But if I did offer my opinion I'd say that letting classes access private collections and then operating with them is poor encapsulation.
Better to hide those details and provide methods to give the information you want without giving away the private details.

Most efficient way to store 5 attributes

So I'm trying to store 5 attributes of an object, which are 5 different integers.
What would be the best way to store these? I was thinking of arrays, but arrays aren't flexible. I also need to be able to retrieve all 5 attributes, so arrays probably won't work well.
Here's some background if it helps: I am currently making a game similar to Terraria (or Minecraft in 2D).
I wanted to store where the object is on the map(x,y), where it is on the screen at the part of the map(x,y), and what type of object it is.
import java.awt.Point
public class MyClass {
private Point pointOnMap;
private Point pointOnScreen;
// ...
}
The Point class binds x & y values into a single object (which makes sense) and gives you useful, basic methods it sounds like you'll need, such as translate and distance. http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html
It is not possible to predict what is the most efficient way to store the attributes without seeing all of your code. (And I for one don't want to :-)) Second, you haven't clearly explained what you are optimizing for. Speed? Memory usage? Minimization of GC pauses?
However, this smells of premature optimization. Wasting lost of time trying to optimize performance on something that hasn't been built, and without any evidence that the performance of this part the codebase is going to be significant.
My advice would be:
Pick a simple design and implement it; e.g. 5 private int variables with getters and setters. If that is inconvenient, then choose a more convenient API.
Complete the program.
Get it working.
Benchmark it. Does it run fast enough? If yes, stop.
Profile it. Pick the biggest performance hotspot and optimize that.
Rerun the benchmarking and profile to check that your optimization has made things faster. If yes, then "commit" it. If not then back it out.
Go to step 4.
I would suggest HashMap where key can be objectId-attributeName and value will be integer value as you have to do retrieval based on key. This will be O(1) operation

Will I have a big performance penalty when I use Reflection api in Android application?

I want to implement a Map of functions. I have several functions for inserting different data in SQLite database (InsertUSER_Data(), InsertMessages()) and so on. I want to create a Map and to call a specific function by a key command. As I see during search there are two approaches for this: anonymous classes and reflection. (e.g. here How to call a method stored in a HashMap? (Java)) I really like the approach based on Reflection API (via a Method type) : Map <String, Method> instead of just using anonymous classes which implement interface. But I have doubts: is it a really big performance overhead in this solution, especially if I'll use it in Android or it's not really significant? Detail explanation will be very helpful.
I cannot answer your exact point, but some basics could help :
The art of knowing the performance beforehand is subtle, difficult and dangerous. The best way to do it is to measure the difference between the two solutions (that could be as simple as System.currentTimeMillis()).
As a rule of thumb, the time passed "in memory" will often be of little importance in terms of performance, in comparison with other things like IO (file or database acesses), remote calls or even something UI elements.
Except if you intend to do (b?)millions of calls, I sincerely doubt that such as small Map would be of consequence. But again, do not believe me, test it.
Finally, could your problem not be solve simply using interfaces ? That would remove this problem, and it is often easier to write, read, and debug. Something like :
interface Actionable {
Result doStuff(Param p);
}
That your various function classes could implement, and that would be possible to call afterwards without knowing exactly what is behind.

Saving a game (Android app.)

This is somewhat of an open question.
I'm in the process of developing a simple game for android and I've gotten to the point where I'm trying to enable thee user to save their progress and return later.
As i'm a beginner, I'm not exactly sure where to start, so I was hoping some of you might have at least some suggestions.
A little info on the setup of the game:
All animation is done in a thread through a canvas and alternation of stored bitmap frames based on a 30 ms loop.
Everything is an object, the characters, the background is simply a 2d array of objects. and each object is generally referenced and created dynamically through a hashmap.
Now how to save? I know I could brute force it, and simply save coordinates and current actions blah blah etc. etc. for each object in each map.
But is there a better way to do this? I've briefly read that in python there's a method of sterilizing objects called "pickle," and there is something similar called "kryo." Am I looking in the right direction?
You should look into Java serialization. It's not perfect, it has problems, but it's the safest, quickest way to turn a complex tree of objects into something that you can save to a file or a db, and load it back when you need.
Else, there's always the possibility to use your own specific serialization using INSERT SQL queries, etc. But be very careful, it's easy to miss parts of what you want to save / restore. One example of that would be to turn your objects tree into XML and save that XML as a file. There are very good 3rd-party libs to map objects to XML and back in Java.
Well.. That's not STERILIZATION, but SERIALIZATION.. Which is a programming technique. And serialization is also the technique you want to use.
Doesn't matter if you use a predefined method or something you write on your own, but the only thing that matters is to loop across the objects and write to the file (or saving structure) the date you need to be later reloaded.
Anyway yes, you're looking the right way.
The best way to do it is implementing a serialization interface. Each object for which the serialize() method is called must save it's data and then call the serialize() method for each child object it owns.

Categories