简体   繁体   中英

Is there a performance impact for using code blocks in Java?

I'm starting to play with OpenGL from Java, and I'm encountering a situation where I need to put a lot of code between many glBegin() and glEnd() calls, and would like for the code to be be auto formatted such that it is easy to see at a glance which code belongs to which glBegin/glEnd.

To accomplish this, I have been using an anonymous code block, like this:

glBegin(GL_QUADS);
{
   glVertex2f(100, 100);
   glVertex2f(100+200, 100);
   glVertex2f(100+200, 100+200);
   glVertex2f(100, 100+200);
}
glEnd();

My question is: are there any performance concerns, even if extremely minor, for using code blocks in this manner? Or is it identical to not using the code blocks at all once the program is compiled?

There should be no cost for using blocks like this. Blocks are a syntactic feature of the language used for scoping purposes and have no associated runtime functionality. Looking at compiled bytecode executed by the JVM, there's no way to tell what the scoping rules of a function are, and so the JVM should give the same performance with and without the blocks.

Feel free to do this if you think it's easier to read. In fact, that should almost always be your priority, unless you have a reason to suspect otherwise.

Hope this helps!

Those countless calls to glVertex impact your performance much more than anything else. That should be your real concern. Look into vertex arrays and vertex buffer objects for a real performance boost. Also your code will look nicer.

If you're not going to declare variables local to the blocks, then don't use local blocks at all. You gain nothing by doing so, other than the very real possibility of causing confusion in the people that has to read and maintain your code, including yourself.

Local blocks are useful for declaring short-lived objects inside a method, objects that only remain in scope for the duration of the block. Even so, nothing guarantees you that they'll get garbage collected before the method ends.

Using local blocks as a performance optimization is moot, you're better off profiling your application and tuning the parts proven to be slow, instead of performing micro-optimizations such as this that will end up making the code harder to read and maintain.

Using local blocks for improving readability, well, it's debatable but it creates the possibility of opening a can of worms regarding scoping problems for the code being executed inside the block, possibly generating some very hard-to-find bugs.

For readability's sake, why not a couple of well-placed comments before and after each glBegin() and glEnd() ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM