Code Optimization Technique: In Programming Language

Code Optimization technique part 1:   Write only those code that makes you better coder.

In this post we will consider loop whose casual use can slow down your program performance.

Note: This post for all of those who write code in any language it is general programming basic concept.

Loop Optimization
The code optimization can be significantly done at loop statement in any language. In loop of the program , specially inner loop is a placed where program spend a large amount of time.

1) Code motion : If there is some expression in the loop , whose result is remain unchanged even after executing the loop for several times then , such an expression will be placed just before the loop.

Bad Practice:

while (i<=max-1)
{
   sum = sum +a[i];
}

Good Practice:

n= max-1
while (i<=n)
{
   sum = sum+a[i];
}

Loop invariant:
It is the technique of avoiding computation /calculation inside loop.

Bad Practice:

for( i=0;i<=10;i++)
{
k= i+a/b;
}

Good Practice:

n=a/b;
for ( i=0; i<=10;i++)
{
  k=i+n;
}

Bad Practice:

for (i=0; i<=10;i++)
{
   add();
}

Good Practice:

for ( i=0; i<=10;i++)
{
// Write definition or inline code of add().
}

Loop Fusion:
– It is technique of measuring several loop into one loop.

Bad Practice:

for ( i=1; i<=10;i++)
{
  for (j=1;j<=10;j++)
  {
   printf ("NIshant");
  }
}

Good Practice:

for ( i=1;i<=100;i++)
{
   printf ("Nishant");
}

 Loop Unrolling:
It is the technique of number of jump and test will be reduced by writing the code two times.

Bad Practice:

int i = 1;
while (i<=100)
{
   a[i] = b[i];
   i++;
}

Good Practice: 

int i = 1;
while (i<=100)
{
   a[i] = b[i];
   i++;
   a[i] = b[i];
   i++;
}

Feel free to comment on above thumbs rule for loop which I follows in my daily coding routine. And any suggestion and any new things from your side is always welcome.

Happy coding:)

Advertisements

2 thoughts on “Code Optimization Technique: In Programming Language

    • int i = 1;
      while (i<=100)
      {
      a[i] = b[i];
      i++;
      }
      Here Loop will execute 101 times because each time i is incremented by 1. so it will execute untill i=101.

      And Here
      int i = 1;
      while (i<=100)
      {
      a[i] = b[i];
      i++;
      a[i] = b[i];
      i++;
      }
      Loop will execute 50 Times because each time i is incremented twice. Like value of i is changes 1, 3, 5, 7,9, so it will reach at 100 after 50 execution.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s