简体   繁体   中英

Do extra code blocks—scopes—slow down execution?

Whenever I comment out my code—I like to have nice and big comments. Upon times the big comments need be nested, I usually add extra indentation. It would—however—be a lot clearer should I be able to use extra code blocks {} to make the indentation more logical.

Let's have a quick example:

// ┌───────────────────┐
// │ COMMENT           │
// └───────────────────┘
{
    // Code in here
}
// ┌───────────────────┐
// │ ;                 │
// └───────────────────┘

Will the {} in this example slow down the speed of a Java program in any way or will they be automatically removed by the compiler? Surely {} is a scope in and of itself, and Java would want to keep that, correct?

If your methods are complex and difficult to understand in one go, try extracting one or more methods from your large method. Note: methods calls are not free, but smaller methods tend to get inlined so you can end up with code which is just as fast even with method calls in your code.

Surely {} is a scope in and of itself, and Java would want to keep that, correct?

The byte code can have frame information but rarely does. Usually there is no way to know from the byte code whether you have used extra { x(); } { x(); } or (x) in your code.

These frames may or may not make a different to the machine code actually generated, but if they are not there, they make no difference.

Most of the time, the most important thing is clarity, you should worry about performance when you have measured you have a problem. The only time you need to worry up front is when time complexity matters, use a strategy with a lower time complexity.

Four different placement directions need be checked per self-contained method.

In that case I would have a loop like

enum Direction {
    NORTH(0, +1), SOUTH(0, -1), EAST(+1, 0), WEST(-1, 0);

    final int x, y;

    Direction(int x, int y) { this.x = x; this.y = y; }
}

for (Direction dir : Direction.values()) {
    // do something with each direction.
}

You can store Direction.values() in a private constant to save a little garbage/allocation.

They won't really slow down anything, as they will be removed by the compiler.

However, rather than writing code like that, you might want to try and extract a function with a good , self-documenting name. It will be much more readable.

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