Create new object or reuse old object Java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a HashMap of "buttons" which can be clicked with the key being the location (x and y coordinates) of the button. Every time new data is received from the database the buttons rearrange themselves and update their positions in the map and other values associated with the "button" object. Currently I have buttons as an immutable object so new buttons need to be created each time I receive new data.
When I thought of a real life example of this (buying a new, different colour version of your house instead of painting the one you already have) it seemed a bit wasteful to keep creating objects instead of just reusing the old ones, is this the best way to do it?

Creating new objects usually means allocating new memory, an operation that is quite expensive and something which should be avoided if a function really needs to be optimized.
It's hard (if not impossible) to say if it will be faster to create new objects or not in your specific case without any code. If we're talking about a list of 10 buttons it wont matter, but if we're talking about a list of trillions on buttons, you should probably try to reassign their values instead.
Below is a small example that illustrates the difference between creating new objects and reassigning a single value of an instance, if I understood you question correctly it should be somewhat similar to your case. The output on my machine can be seen below.
package org.stackoverflow;
import java.util.ArrayList;
public class Example {
public static class MyObject {
private double value;
public MyObject(double value) {
this.setValue(value);
}
public final void setValue(double value) {
this.value = value;
}
public double getValue() {
return this.value;
}
}
public static void main(String[] args) {
long start = 0;
ArrayList<MyObject> objects = new ArrayList<MyObject>();
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; ++i) {
objects.add(new MyObject(Math.random()));
}
System.out.println("Time to create 1.000.000 objects: "
+ Long.toString(System.currentTimeMillis() - start)
+ " ms.");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; ++i) {
objects.get(i).setValue(Math.random());
}
System.out.println("Time to reassign 1.000.000 objects: "
+ Long.toString(System.currentTimeMillis() - start)
+ " ms.");
}
}
Output
Time to create 1.000.000 objects: 323 ms.
Time to reassign 1.000.000 objects: 31 ms.

Related

HashMap performs better than array? [duplicate]

Is it (performance-wise) better to use Arrays or HashMaps when the indexes of the Array are known? Keep in mind that the 'objects array/map' in the example is just an example, in my real project it is generated by another class so I cant use individual variables.
ArrayExample:
SomeObject[] objects = new SomeObject[2];
objects[0] = new SomeObject("Obj1");
objects[1] = new SomeObject("Obj2");
void doSomethingToObject(String Identifier){
SomeObject object;
if(Identifier.equals("Obj1")){
object=objects[0];
}else if(){
object=objects[1];
}
//do stuff
}
HashMapExample:
HashMap objects = HashMap();
objects.put("Obj1",new SomeObject());
objects.put("Obj2",new SomeObject());
void doSomethingToObject(String Identifier){
SomeObject object = (SomeObject) objects.get(Identifier);
//do stuff
}
The HashMap one looks much much better but I really need performance on this so that has priority.
EDIT: Well Array's it is then, suggestions are still welcome
EDIT: I forgot to mention, the size of the Array/HashMap is always the same (6)
EDIT: It appears that HashMaps are faster
Array: 128ms
Hash: 103ms
When using less cycles the HashMaps was even twice as fast
test code:
import java.util.HashMap;
import java.util.Random;
public class Optimizationsest {
private static Random r = new Random();
private static HashMap<String,SomeObject> hm = new HashMap<String,SomeObject>();
private static SomeObject[] o = new SomeObject[6];
private static String[] Indentifiers = {"Obj1","Obj2","Obj3","Obj4","Obj5","Obj6"};
private static int t = 1000000;
public static void main(String[] args){
CreateHash();
CreateArray();
long loopTime = ProcessArray();
long hashTime = ProcessHash();
System.out.println("Array: " + loopTime + "ms");
System.out.println("Hash: " + hashTime + "ms");
}
public static void CreateHash(){
for(int i=0; i <= 5; i++){
hm.put("Obj"+(i+1), new SomeObject());
}
}
public static void CreateArray(){
for(int i=0; i <= 5; i++){
o[i]=new SomeObject();
}
}
public static long ProcessArray(){
StopWatch sw = new StopWatch();
sw.start();
for(int i = 1;i<=t;i++){
checkArray(Indentifiers[r.nextInt(6)]);
}
sw.stop();
return sw.getElapsedTime();
}
private static void checkArray(String Identifier) {
SomeObject object;
if(Identifier.equals("Obj1")){
object=o[0];
}else if(Identifier.equals("Obj2")){
object=o[1];
}else if(Identifier.equals("Obj3")){
object=o[2];
}else if(Identifier.equals("Obj4")){
object=o[3];
}else if(Identifier.equals("Obj5")){
object=o[4];
}else if(Identifier.equals("Obj6")){
object=o[5];
}else{
object = new SomeObject();
}
object.kill();
}
public static long ProcessHash(){
StopWatch sw = new StopWatch();
sw.start();
for(int i = 1;i<=t;i++){
checkHash(Indentifiers[r.nextInt(6)]);
}
sw.stop();
return sw.getElapsedTime();
}
private static void checkHash(String Identifier) {
SomeObject object = (SomeObject) hm.get(Identifier);
object.kill();
}
}
HashMap uses an array underneath so it can never be faster than using an array correctly.
Random.nextInt() is many times slower than what you are testing, even using array to test an array is going to bias your results.
The reason your array benchmark is so slow is due to the equals comparisons, not the array access itself.
HashTable is usually much slower than HashMap because it does much the same thing but is also synchronized.
A common problem with micro-benchmarks is the JIT which is very good at removing code which doesn't do anything. If you are not careful you will only be testing whether you have confused the JIT enough that it cannot workout your code doesn't do anything.
This is one of the reason you can write micro-benchmarks which out perform C++ systems. This is because Java is a simpler language and easier to reason about and thus detect code which does nothing useful. This can lead to tests which show that Java does "nothing useful" much faster than C++ ;)
arrays when the indexes are know are faster (HashMap uses an array of linked lists behind the scenes which adds a bit of overhead above the array accesses not to mention the hashing operations that need to be done)
and FYI HashMap<String,SomeObject> objects = HashMap<String,SomeObject>(); makes it so you won't have to cast
For the example shown, HashTable wins, I believe. The problem with the array approach is that it doesn't scale. I imagine you want to have more than two entries in the table, and the condition branch tree in doSomethingToObject will quickly get unwieldly and slow.
Logically, HashMap is definitely a fit in your case. From performance standpoint is also wins since in case of arrays you will need to do number of string comparisons (in your algorithm) while in HashMap you just use a hash code if load factor is not too high. Both array and HashMap will need to be resized if you add many elements, but in case of HashMap you will need to also redistribute elements. In this use case HashMap loses.
Arrays will usually be faster than Collections classes.
PS. You mentioned HashTable in your post. HashTable has even worse performance thatn HashMap. I assume your mention of HashTable was a typo
"The HashTable one looks much much
better "
The example is strange. The key problem is whether your data is dynamic. If it is, you could not write you program that way (as in the array case). In order words, comparing between your array and hash implementation is not fair. The hash implementation works for dynamic data, but the array implementation does not.
If you only have static data (6 fixed objects), array or hash just work as data holder. You could even define static objects.

Functional Operations to iterate arrays in Java 8 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
So in an attempt to keep up with the times, I would like to learn what I can about Java 8's new functional operations. Beyond the opinions of which looks nicer, which is totally opinion based, would someone like to describe in detail the positives(and possibly negatives) in using Java 8's new functional programming style to iterate arrays?
This is what I mean:
Pre-Java 8:
for(Object item: itemList){
item.doSomething();
}
Java 8:
itemList.stream().forEach((item) -> {
item.doSomething();
});
The answers have enlightened me, so I will write something to demonstrate it's potential.
static int pos = 0;
public static void main(String[] args) {
List<Worker> workers = Arrays.asList(new Worker[1000]);
workers.replaceAll(worker -> new Worker(pos++));
workers.parallelStream().forEach(Worker::startJob);
}
public static class Worker {
final int pos;
public Worker(int pos) {
this.pos = pos;
}
public synchronized void startJob() {
try {
wait(100);
} catch (InterruptedException ex) {
Logger.global.log(Level.SEVERE, null, ex);
}
System.out.println("Finished... " + pos);
}
}
Only a partial answer, but the general point of the iterators is moving from external iteration to internal iteration. The foreach just a replacement, but consider something like the following (from Java 8 Lambdas) simulating the throwing of two dice:
public Map < Integer, Double > parallelDiceRolls() {
double fraction = 1.0 / N;
return IntStream.range( 0, N) .parallel()
.mapToObj( twoDiceThrows())
.collect( groupingBy( side -> side, summingDouble( n -> fraction)));
}
This is running a parallel operation against the stream, removing all external iteration requirements and all manual threading requirements. It replaces 50-60 lines of code.
It also moves from a focus on how to accomplish something (such as the OP's pre-Java 8 example) to what to accomplish.
Consider a Artist class that has an .isFrom(String) method. In the OP's first example, to count how many are from Liverpool, the code would be something like:
int count = 0;
for (Artist artist : allArtists) {
if (artist.isFrom("Liverpool")) {
count++;
}
}
Notice that the the desire to accumulate is lost in the loop and the filtering. Contrast with:
allArtists.stream()
.filter(artist -> artist.isFrom("Liverpool")
.count();
Now the logic is clear -- a filtering and a count. The iteration is now internal rather than external.
There are many additional examples, rationales, and preferences. But I think it is more than "beauty" -- it is a focus on the what, not the how when one considers iteratation.

Looping through Object of Objects in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have an object which in turn contains other objects. Now I have to iterate through this main object and then pick each object and then iterate through them to find out whether any empty fields are present in them. If the object itself is empty, I have to cut it out of main object. Any thoughts on this please.
public class Transactions {
private Integer totalTransactionCount = null;
private List<Transaction> transactionsList = new ArrayList<Transaction>();
}
public class Transaction {
private String amount = null;
private Foreign foreign = null;
}
public class Foreign {
private String amount = null;
private String commissionAmount = null;
private String exchangeRate = null;
}
Now I have a Transaction object with me and I have to loop throught each of its fields and in turn loop through their fields to find out any null/empty fields.
pseudo code for looping through a list of lists:
for each (innerList in outerList) do
if(innerlist.size == 0) then
//Code for removing empty inner lists.
else
for each ( object in innerList) do
//Check if objects are empty as well and remove it
end for
end if
end for
EDIT: Pointing out lack of research.
I would like to point out that you haven't really done your research properly, simply by googling iterate list of object as well as iterate list of list of object I got plenty of solutions.
Not to mention a question already asked here on Stack Overflow, please read the first answer of this post

Calling methods on a List object of type Class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have made a List with the type of a child class. Why can't I call on the methods defined in the child class?
int desktopID = 0;
Random randomID = new Random();
List<MessageHandler> test = null;
for(int i = 0; i < 1000; i++){
desktopID = randomID.nextInt(10);
System.out.println(desktopID);
test.storeMessage("Message Number: "+ i, desktopID);
}
System.out.println(test.getRecentMessage(desktopID).toString());
Some Background
It not exactly clear what your asking... but it sounds like you want to know why you can't call the methods defined in MessageHandler from your list test of type List<MessageHandler>.
The definition of List<E> in the javadoc explains that the parameter E is the type that the list can contain. The add(E e) method, for example, will inherit from this and only allow items of type E to be added to the list. What this does not mean is that you can call the methods defined within class E from the List<E> object.
For example, I would not be able write this (where .getRGB() is a method from the Color Class):
List<Color> colorList = new ArrayList<>;
colorList.getRGB();
However I would be able to write this. Notice how I added a Color object to the list and am getting it from the list to call the method on it:
List<Color> colorList = new ArrayList<>;
colorList.add(Color.Red);
colorList.get(0).getRGB();
To Answer Your Question
What this means for you, then, is that you should not call your .storeMessage(...) and .getRecentMessage(...) on your list test. Rather you should be creating an object of type MessageHandler, calling your store method on that, and then adding it to the list. Once you've done that you can loop over the list again, get each object from the list, and output the message.
Try this:
int desktopID = 0;
Random randomID = new Random();
// Note that I'm instantiating the list before using it!
List<MessageHandler> test = new Arraylist<>;
for(int i = 0; i < 1000; i++){
desktopID = randomID.nextInt(10);
System.out.println(desktopID);
// Create a MessageHandler object and set the message.
MessageHandler handler = new MessageHandler();
handler.storeMessage("Message Number: "+ i, desktopID);
// Add that method to your list
test.add(handler);
}
// This is a foreach loop. Very useful! Will iterate over each element in order.
for(MessageHandler handler : test){
System.out.println(handler.getRecentMessage(desktopID).toString());
}
(I've assumed that your MessageHandler object has a default constructor.)

Converting Java code to model view controller architecture pattern [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have written some code in java to give the some of the numbers 1 to 10 and then also display the average. I would like to change this to the model view controller method(thats what the tutor wants). We only had one lesson on it and i dont really understand how do change it. If someone could go through this and show me how(as if they were trying to teach a 5 year old) that would be great.
//JAVA CODE
public class Ex4 {
public static void main(String[] args) {
int sum = 0;
int average = 0;
for (int i=1; i < 10; i++){
sum = sum + i;
average = sum/i;
}
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
MVC is a basic pattern where you separate the model (data), view (display), and controller (logic) into different files and directories.
Here is an illustration of this model:
Here is an example of how that might look with your current code:
Controller Class (with main method included):
public class Ex4Controller {
//You could create a second controller,
//and put the main method there,
//then create a controller object.
public static void main(String[] args) {
//Initialize model
Ex4Model number = new Ex4Model(0,0.0);
//Execute business logic
Ex4Controller.getSumAndAverage(number);
//Set view
Ex4View.printSum(number.sum, number.average);
}
//Logic method
private static void getSumAndAverage(Ex4Model numbers){
for (int i=1; i < 10; i++){
//Here the controller interfaces with
//the model
numbers.sum = numbers.sum + i;
numbers.average = numbers.sum/i;
}
}
}
The controller class interfaces with both the model and the view. This class is where you do all the processes, and update the model or view. Any logic done, is going to be done in this class. If you wanted to get the mean of the numbers, you would write a method called getmean() in this class. Data manipulation is ONLY done here.
This is the Model class:
public class Ex4Model {
public int sum = 0;
public double average = 0;
//Custom constructor to set values
public Ex4Model(int sum, double average){
this.sum = sum;
this.average = average;
}
}
This class is used to hold the data. No logic is done here. This is a basic data structure that you use to house the data. This class does not interface with the view.
This is your view class:
public class Ex4View {
public static void printSum(int sum, double average){
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
This isn't a true view, but it's the best demonstration considering the circumstances. With Java, you would put your swing files here. The job of these files is to display the data. You'll notice that the controller passes all the data to this class, rather than accessing the data from the model.
This will output to the console:
The sum is 45
The average is 5.0
Something to keep in mind with MVC, is that you can have multiple controllers, models, and views. This is a very simple example. By using MVC, developers & programmers are able to better organize the data. They know where everything is being done, rather than having views manipulate data in some area's, and not in others.
I hope this makes sense.
As a (very) rough guideline:
Model: Stores the data. In this case, the sum and the average.
View: Displays the data. In this case, writing the data out with System.out. When the model changes, update the display (write the new values out).
Controller: Manipulates the data. In this case, taking an array of ints, computing sum and average, and giving the results to the model.
So overall, Controller computes sum & average, gives those values to Model. View is notified that Model changed. View displays Model's values.
Create 3 classes:
Let say Ex4Model, which just has 2 member variables in it called sum and average, and the corresponding get and set methods for each. This will hold your data.
We can then create the view, lets say Ex4View, which has a method say called render(Ex4Model model) which outputs the stuff you want from the model, in your case the sum and average.
Then you can create the controller, Ex4Controller, which has a method calculate(). Inside it it performs the calculations and feeds them to the model (in this simple example you can just create a new instance of it) and then calls render() on the view.
The rest is for you to join together, this is your homework.

Categories