0

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?

Community
  • 1
  • 1
nllsdfx
  • 900
  • 14
  • 30
  • 3
    Don't worry about efficiency until you can see that your program isn't performing fast enough to meet your needs. At that point, make optimizations to the specific parts that are causing bottlenecks. Trying to micro-optimize everything you write will just waste a lot of time and probably make your code harder to read. – nhouser9 Apr 13 '17 at 17:54
  • 1
    Java does *not* pass objects by value. Java does not pass objects at all. It can pass *references* to objects by value. In terms of performance, unless you're in a bottleneck, concerns over negligible differences in runtime costs are outweighed by understandability of code. – Andy Thomas Apr 13 '17 at 17:56
  • 1
    do you want to allow the DataReader to read more than one Data object? if so I would implement the public void read(Data data){...} (1 to Many relationship). If the DataReader only uses a single Data object then passing it via the constructor makes sense (1 to 1 relationship). – RAZ_Muh_Taz Apr 13 '17 at 17:57

1 Answers1

1

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.

dodo
  • 156
  • 10