Does object creation speed up the virtual machine?

Take a look at this piece of code:

MessageParser parser = new MessageParser();
for (int i = 0; i < 10000; i++) {
    parser.parse(plainMessage, user);
}

      

For some reason, it starts SLOWER (about 100ms) than

for (int i = 0; i < 10000; i++) {
    MessageParser parser = new MessageParser();
    parser.parse(plainMessage, user);
}

      

Any ideas why? The tests were repeated many times, so it wasn't just random. How to create an object 10,000 times faster than creating it once?

+2


source to share


4 answers


Since Java has a collection of garbage collectors and can quickly identify (in a loop) that it does not use the same object / memory space, so the GC cost is practically zero. On the other hand, your long-lived object will survive the passage of generations over the nursery and should be carried over into the main generation.



Thus, you cannot really assume performance without running tests to measure it.

+10


source


There may be some logic to clear the internal state when the parser is called later.



Did the GC pass during the test? It's pretty cheap to instantiate a new object, and it's not a fair comparison if you don't take the time to delete all the objects you created in the faster case.

0


source


I have no idea what it does MessageParser

or where it comes from. It could be a "leak" from the inside. Another possibility is that the object gets further from the data generated during parsing. This means that you will most likely get a missing TLA. Also, if it MessageParser

saves internal state and travels to a generation, the GC mechanic of noting that it is referencing new data can be a problem ("card counting" is jargon that comes to mind).

0


source


What happens if you check the first example when limiting the scope parser

, i.e.

{
    MessageParser parser = new MessageParser();
    for (int i = 0; i < 10000; i++) {
        parser.parse(plainMessage, user);
    }
}
// `parser` no longer visible

      

I expect this to be the fastest since only one object needs to be created and the VM still knows it parser

might be gc'd right after the loop.

0


source







All Articles