patternjavaMinor
Does this loop unrolling make sense?
Viewed 0 times
thisloopunrollingmakesensedoes
Problem
I am coding a Hanning filter which is a recursive relation:
And here is my code were I attempt to unroll 3 times:
Would this help at all with an OoO superscalar processor? Is 3 the right amount of times to unroll? Thanks
y[i] = 0.25*(x[i] + 2*x[i-1] + x[i-2])And here is my code were I attempt to unroll 3 times:
public void HanningFilter(float[] array) {
int len = array.length;
int i;
for (i = 2; i < len-3; i+=3) {
array[i] = 0.25f*(array[i] + 2*array[i-1] + array[i-2]);
array[i+1] = 0.25f*(array[i+1] + 2*array[i] + array[i-1]);
array[i+2] = 0.25f*(array[i+2] + 2*array[i+1] + array[i]);
}
//Clean-up at the end
for (int j = i; j < len; j++) {
array[i] = 0.25f*(array[i] + 2*array[i-1] + array[i-2]);
}
}Would this help at all with an OoO superscalar processor? Is 3 the right amount of times to unroll? Thanks
Solution
No, rule of thumbs for this case:
Loop unrolling only makes sense if you profiled the code and found the unrolled version to be faster then the normal version.
I guess you're coming from a C background, so please don't try to bring C-habits to Java. Java is different, always go for readability first.
The Java naming conventions dictate that function names are lowerCamelCase.
Also the name
What you're doing here is absolutely unnecessary. Java allows declarations of variables inside the for and there's no need to define a variable for the condition.
Naming loop variables
- Never guess optimizations, use a profiler
- You're not smarter then the JIT compiler
Loop unrolling only makes sense if you profiled the code and found the unrolled version to be faster then the normal version.
I guess you're coming from a C background, so please don't try to bring C-habits to Java. Java is different, always go for readability first.
public void HanningFilter(float[] array) {The Java naming conventions dictate that function names are lowerCamelCase.
Also the name
array is a bad name, more appropriate would be a name like data or input.int len = array.length;
int i;
for (i = 2; i < len-3; i+=3) {What you're doing here is absolutely unnecessary. Java allows declarations of variables inside the for and there's no need to define a variable for the condition.
for (int idx = 2; idx < data.length; idx++) {Naming loop variables
idx or counter is not very famous, I prefer it to i.Code Snippets
public void HanningFilter(float[] array) {int len = array.length;
int i;
for (i = 2; i < len-3; i+=3) {for (int idx = 2; idx < data.length; idx++) {Context
StackExchange Code Review Q#30603, answer score: 8
Revisions (0)
No revisions yet.