Search code examples
javascriptperformanceloopscplexopl

Performance Issues with loops in JavaScript


I'm having huge performance problems with my JavaScript code. I try to pre-process data for a Cplex-Model in OPL, the code is written in JavaScript.

I already tried to speed it up by adding the first if-clause (if A[1][3]="", A[1][k] ="" for every k > 3) , but it still takes my computer more than 2 hours to process just this code...

Jnr = 1000,
Mnr = 35;
while (j <= Jnr) {
  while (i <= Mnr) {
    while (k <= Mnr) {
      if (A[j][k] == "") {
        break;
      } else if (A[j][k] == I[i].name) {
        counter[j][i] = counter[j][i] + 1;
      }
      k = k + 1;
    }
    k = 1;
    i = i + 1;
  }
  i = 1;
  j = j + 1;
}
j = 1;

Is there anyway to speed up the process?

I appreciate your help


Solution

  • It's not a very good idea to use scripting for big loops. If you write that directly in OPL this will be much faster:

    int Jnr = 1000;
    int Mnr = 35;
    
    tuple t
    {
    string name;
    }
    
    t I[i in 1..Mnr]=<"A">;
    
    string A[i in 1..Jnr][j in 1..Mnr]=((i+j)%2==0)?"A":"B";
    int counter[1..Jnr][1..Mnr];
    
    execute
    {
    var i=1;
    var j=1;
    var k=1;
    
    while (j <= Jnr) {
      while (i <= Mnr) {
        while (k <= Mnr) {
          if (A[j][k] == "") {
            break;
          } else if (A[j][k] == I[i].name) {
            counter[j][i] = counter[j][i] + 1;
          }
          k = k + 1;
        }
        k = 1;
        i = i + 1;
      }
      i = 1;
      j = j + 1;
    }
    j = 1;
    }
    
    
    int counter2[i in 1..Jnr][j in 1..Mnr]=sum(k in 1..Mnr) (I[k].name==A[i][k]);
    
    execute
    {
    counter2;
    }
    
    
    assert forall(i in 1..Jnr,j in 1..Mnr) counter[i][j]==counter2[i][j];
    

    counter takes 9 s on my machine, whereas counter2 takes 0.3 s