Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Performance is a black art and at the end of the day, you have to profile it to be sure. Don't worry about performance until you have reason to believe it's an issue.

That said, variables on the stack are super lightweight - even if a variable is in a tight loop, declaring the variable inside the loop will not be an issue, since the compiler will generally optimize it out.

Only when the object is (entirely or partly) on the heap or involves contended resources like locks will there be a performance impact and you should measure it to see if the impact is even worth worrying about.

Performance is a black art and at the end of the day, you have to profile it to be sure. Don't worry about performance until you have reason to believe it's an issue.

That said, variables it's not bad practice. In fact it's good practice to keep variable declarations close to their usage to avoid accidental shared mutable state. Variables on the stack are super lightweight - even if a variable is in a tight loop, declaring the variable inside the loop will not be an issue, since the compiler will generally optimize it out.

Only when the object is (entirely or partly) on the heap or involves contended resources like locks will there be a performance impact and you should measure it to see if the impact is even worth worrying about.