Reputation: 940
I have an object to read data:
DataReader dataReader = new DataReader();
And object to read:
Data data = new Data();
I can read data like so:
dataReader.read(data);
Or I can pass data
to dataReader
constructor and read it within dataReader
object.
What is more efficient?
And what is better in case read() method is implemented like this:
public void read(Data data) {
this.readString(data);
this.readString(data);
}
And method readString(Data data)
:
private void readString(Data data) {
data.nextLine();
}
Meaning, is it better to have one local data object and call its methods or pass it several times as methods argument when java passes object by value not reference? What works faster and consumes less memory?
Upvotes: 0
Views: 54
Reputation: 156
I am a little unsure as to what you mean for the second part of your question, but if you mean what I think then this should answer it.
Calling the method in your constructor or your method is entirely dependent on usage. For this case, are you going to be reading this data repeatedly? If you are, then creating one instance of a DataReader
would be more efficient than creating one for each read, so using the method repeatedly on one instance would be more efficient. If you are only using it once, then you don't want to have useless object instances hanging around in memory after they are done with, so creating a temporary instance and reading in the constructor would be more efficient.
But as the comments say, these things are rarely concerns for optimisation and make little impact. In theory it's interesting, but in practice don't worry about it unless you have to.
Upvotes: 1