问题
I'm trying to speed up the startup for my program, and noticed I had a method that was acting a little strange. The program itself is a Lightweight Java Game Library application that reads in points from a file, and renders them. The method of note is the method that reads from the file.
What's curious about the method is I call it twice during my tests, where the first call takes 2837ms to complete, and the second only takes 1704ms.
The difference between the two calls are minimal. The difference is the second call reads through half the file before beginning any operations with the file, while the first skips a single line before starting.
This is the method in question:
private void initData(final int type) throws IOException {
final List<Vertex> top = new ArrayList<Vertex>();
final List<Vertex> bot = new ArrayList<Vertex>();
final BufferedReader input = new BufferedReader(new FileReader(location));
if(type == 1) {
while (!input.readLine().contains("lens"));
} else {
input.readLine();
}
while (input.ready()) {
final Scanner in = new Scanner(input.readLine());
while (in.hasNextFloat()) {
final float x = in.nextFloat();
final float y = in.nextFloat();
top.add(new Vertex(x, y, in.nextFloat()));
bot.add(new Vertex(x, y, in.nextFloat()));
in.nextFloat();
}
if ((in.findInLine("[lens]") != null)
|| (in.findInLine("[thin]") != null)
|| (in.findInLine("[thick]") != null)
|| (in.findInLine("[end]") != null)) {
break;
}
}
input.close();
final long start = Diagnostics.getCurrentTime();
mergeAndSort(top, bot);
System.out.println("Sort: " + (Diagnostics.getCurrentTime() - start));
}
The output I get from this is:
Sort: 15
Initializing: 2836
Sort: 4
Initializing: 1704
Reading info: 27
Where all numbers are in milliseconds. You'll notice the Sort takes almost a quarter of the time during the second run through. The sort method is identical each time it's run.
The class the methods are contained in is newly created each time the method is called.
So, I'm curious as to why the first call takes almost a full second longer than the second call.
回答1:
The fact that processing half of the file takes approximately half the time of processing the whole file leads me to believe that most of the time is spent in object creation (instantiation of the Vertex class).
However, the only way to be really sure what is going on is to use a profiling tool.
I'd Start with JVisualVM, which is part of the JDK distribution.
来源:https://stackoverflow.com/questions/16775170/second-method-call-takes-far-less-time-than-the-first