Faster, simpler return statements

17 Jan 2006

Another "code simplification" PMD rule! Suppose you've got some code at the end of a method like this:

int foo() {
 // lots of code...
 int buz = getBuz();
 return buz;
}

That's fine, but it could be consolidated into this:

int foo() {
 // lots of code...
 return getBuz();
}

This simple change saves you six bytes; it gets rid of two instructions, an istore and an iload. And some benchmarking shows that it's about 30% faster! [1/24/06 update: this speed increase disappears when you run the JVM with the -server option, and it may also go away on JVMs newer than 1.4. Thanks to Allan Caplan and Pekka Enberg for the helpful discussion!]

This rule is UnnecessaryLocalBeforeReturn; it's in the PMD "design" ruleset. It might change a bit in the future; Elliotte Rusty Harold had a suggestion about it being a bit too aggressive.

Support PMD, get the book, 'PMD Applied'!