Thursday 6 January 2022

Explain Loop inversion in Java

 Loop inversion is a compiler optimization technique where a while loop is replaced by an if block containing a do..while loop.

How does loop inversion improve performance?

Let me explain with an example.
int i = 0;
int a[] = new int[10];
while (i < 10) {
	a[i] = 0;
	i++;
}

Post loop inversion optimization, above code will be transformed like below.

int i = 0;
int a[] = new int[10];

if (i < 10) {
	do {
		a[i] = 0;
		i++;
	} while (i < 10);
}

How this transformation improve performance?

When the value of i is 10, the processor need not execute a goto instruction to come out of the loop (which is required in the first case). This improves performance. By nature, any jump in the code causes a pipeline stall, which is a detriment to performance.

 

Reference

https://en.wikipedia.org/wiki/Pipeline_stall



You may like

Interview Questions

How to specify jar files in command line?

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

No comments:

Post a Comment