sbook
sbook

Reputation: 841

Java Efficiency: Object Assignment & Method Call vs. Inline Method Call

I'm working on an application with a 3D viewport which refreshes 30 times a second (or at least tries to render that fast). Unfortunately, the code is complicated enough that simply converting it to test for the performance effect would take quite a while, but the two conditions I'd be comparing are as follows:

ObjectToRender p = objectsToRender.get(i);
p.render();

as opposed to:

objectsToRender.get(i).render();

I'm sure this sounds like a severe case of micro-optimization but, as noted above, this code is constantly being called and has zero outside factors to influence its performance (Disk I/O, Network, etc).

Upvotes: 0

Views: 879

Answers (5)

rsp
rsp

Reputation: 23373

The objectsToRender.get(i) part of your code might be optimised by using an iterator to loop over all the objects to render:

iterator.next().render();

or, if the list of objects is stable, convert it to an ObjectToRender[] once and index directly:

objectsToRender[i].render();

Upvotes: 0

Bill K
Bill K

Reputation: 62789

There shouldn't be a difference, but I've seen performance differences where I didn't think I should see one.

As you said though, it seems like a micro-optimization and you might get more of a bang by looking for much larger optimizations such as code restructuring or even going to a different graphics toolkit.

If you care about frame rate, you should be displaying or logging your frame rate and have some standardized target for a given pre-programmed test. Once you've done this, testing minor changes should give you immediate feedback regarding various tweaks.

Don't make "Performance Enhancements" without the ability to measure them. It's like you are lost and are suggesting increasing your driving speed to 40 mph over the speed limit because you don't have time to stop and ask for directions.

Upvotes: 2

Mihir Mathuria
Mihir Mathuria

Reputation: 6549

Most modern compilers are smart enough to generate a very optimized byte code. I doubt the above 2 calls should make any difference. In fact, they prolly will generate the same byte code.

Upvotes: 1

Steve B.
Steve B.

Reputation: 57333

The change you suggest shouldn't mattern, although you might get an improvement from moving from indexed-based list access (which is what I assume you're using with "get(i)") to array access.

Upvotes: 0

Darron
Darron

Reputation: 21620

I would expect these two pieces of code to JIT compile to exactly the same machine code, assuming that you don't use "p" anywhere after this fragment.

Upvotes: 7

Related Questions