For loop optimizing

For loop optimizing

For loop optimising solution for java php bash or any other synthax-compatible language with test example

For loop optimizing

Note

In this article test application listed below was written for J2ME devices and all test results was taken from running application on a real Nokia mobile phone. Applying this optimisation on any other platform or any different language may take effect on the results.

You can try to use optimised loop definitions in PHP, Bash, C++ or any synthax-compatible language, write some tests and check the results.

Basics

Usual loop looks like this:

1
2
3
    for (int i = 0; i < 9000000; i++) {
      /* do something */
    }

So, let’s invert loop counter definition:

1
2
3
    for (int i = 8999999; i >= 0; i--) {
      /* do something */
    }

That’s it. Using this definitions we can write some tests:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import javax.microedition.midlet.*;

public class Application extends MIDlet {

  public void startApp() {
    long start, end;
      
    /* Обычный цикл */
    start = System.currentTimeMillis();
    for (int i = 0; i < 9000000; i++) {
      /* do something */
    }
    end = System.currentTimeMillis();
    System.out.println("Normal loop: " + (end - start) + " milliseconds");
      
    /* Оптимизированный цикл */
    start = System.currentTimeMillis();
    for (int i = 8999999; i >= 0; i--) {
      /* do something */
    }
    end = System.currentTimeMillis();
    System.out.println("Optimized loop: " + (end - start) + " milliseconds");
      
    System.out.println("\n");
    destroyApp(true);
  }
  
  public void pauseApp() {
    notifyPaused();
  }
  
  public void destroyApp(boolean unconditional) {
    notifyDestroyed();
  }
}
Поиск по сайту

Результаты поиска

Начните вводить запрос. Можно искать по названию, описанию, тексту и тегам.