Should I use nested blocks to improve performance

I have been learning about stack and heap and particularly the stack with its LIFO approach.

Does this work with nested blocks within methods and can this be used to improve performance e.g.

public void Test() {
    int i = 5;
    // do something with i

    int j = 5;
    // do something with j
}

In this example, only at the end of the method will i and j be freed from the stack.

Would the following be more efficient? (i know its a simple procedure.....) or would the effort of freeing be more then saving on size of the stack?

public void Test() {
    {
        int i = 5;
        // do something with i
    }
    {
        int j = 5;
        // do something with j
    }
}

This is solely for example purposes, I know i could refactor this etc. I am only interested in what happens to memory in a method....

Jon Skeet
people
quotationmark

The stack is allocated for the whole of the method call anyway.

There are some subtle cases where adding extra blocks could help, in terms of captured variables - if you have two lambda expressions, one of which captures i and one of which captures j, then in your first case you'd end up with a synthesized class which captures both variables, whereas in your second case you'd end up with two classes... at least in the current implementation.

Without variable capture, it's at least possible that the JIT could notice that you only use one variable at a time, and optimize to reuse the same stack space for both.

It's very rare that micro-optimizations like this have a significant performance impact, but they can have a very significant readability impact... so I would only start making your code less readable when:

  • You have robust performance tests in place
  • You have a concrete performance goal in mind (so you know when you're done)
  • You have narrowed down where the bottleneck is
  • You have proved that the reduction in readability provides a significant boost in performance

people

See more on this question at Stackoverflow