Variable initialisation
Which is a more efficient way to declare the movie object, inside a loop or outside assigning new values each iteration?
ArrayList开发者_如何学编程<Movie> localMovies = new ArrayList<Movie>();
for (File file : listOfFiles) {
Movie movie = new Movie();
movie.setTitlePattern(filePattern);
localMovies.add(movie);
}
Or
ArrayList<Movie> localMovies = new ArrayList<Movie>();
Movie movie = new Movie();
for (File file : listOfFiles) {
movie.setTitlePattern(filePattern);
localMovies.add(movie);
}
I don't think efficiency is the key point here. The key point is correctness.
The two snippets do different things.
The first version populates the list with different
Movie
objects.The second version populates the list with multiple references to a single
Move
object. You then proceed to change that object's title pattern. So when the loop finishes you will have N references to the same object, and the title pattern for that object will be the will be the last one set.
Though it is not possible to say for sure without more context, the second version looks incorrect ... it doesn't do what (I think) you are trying to do.
Having said that, the "incorrect" version of your code is probably a bit faster. Whether the difference is significant (worth worrying about) depends on the context. And the question is moot anyway.
If you were to compare the performance of these two "correct" versions:
ArrayList<Movie> localMovies = new ArrayList<Movie>();
for (File file : listOfFiles) {
Movie movie = new Movie();
movie.setTitlePattern(filePattern);
localMovies.add(movie);
}
and
ArrayList<Movie> localMovies = new ArrayList<Movie>();
Movie movie;
for (File file : listOfFiles) {
movie = new Movie();
movie.setTitlePattern(filePattern);
localMovies.add(movie);
}
there would most likely be no detectable difference.
You'd better initialize the Movie object inside the for loop unless you want the list to hold multiple references to just one single Movie object. This has nothing to do with efficiency and all to do with bug-free coding. Feel free to declare the Movie object before or inside the loop.
For efficiency, the second one, as it does not have to call and execute the constructor each time.
For correctness, though, you probably want the first one, as the second one gives you many times the same object in the list.
精彩评论