¿Why is my screen slowing down, is there any way to avoid this?

edited December 2017 in Questions about Code

Here´s my code. It´s a simple-animated-3D fractal. The screen, slow down while it´s running. how can I avoid that? Here´s my code.

float i=1;
void setup() {
  fullScreen(P3D);
}

void draw() {
  background(255);
  drawCircle(width/2, height/2, i++/50);
}

void drawCircle(float x, float y, float radius) {
  stroke(0);
  noFill();
  ellipse(x, y, radius, radius);
  pushMatrix();  
  translate(x, y);
  rotate(i++/50000);
  box(radius);
  popMatrix();
  if (radius > 2) {
    drawCircle(x + radius/2, y, radius/2);
    drawCircle(x - radius/2, y, radius/2);
  }
}

Answers

  • edited December 2017 Answer ✓

    Why would an increasing recursive function run slower and slow?

    Well, let's add a simple counter calls that counts how many times "drawCircle" is being called each frame.

    float i=1;
    int calls=0;
    void setup() {
      fullScreen(P3D);
      frameRate(30);
    }
    
    void draw() {
      calls=0;
      background(255);
      drawCircle(width/2, height/2, i++/50);  
      println(frameCount, calls);
    }
    
    void drawCircle(float x, float y, float radius) {
      calls++;
      stroke(0);
      noFill();
      ellipse(x, y, radius, radius);
      pushMatrix();  
      translate(x, y);
      rotate(i++/50000);
      box(radius);
      popMatrix();
      if (radius > 2) {
        drawCircle(x + radius/2, y, radius/2);
        drawCircle(x - radius/2, y, radius/2);
      }
    }
    

    Here are some of the results....

    1 1
    
    51 3
    
    76 7
    
    100 7
    
    101 15
    
    126 31
    
    151 63
    
    176 127
    
    201 255
    
    226 511
    
    251 1023
    
    276 2047
    
    301 4095
    
    326 8191
    
    351 16383
    
    376 32767
    

    ...so, after ~12 seconds, you are calling drawCircle 32767 times per frame.

    That is why it is slowing down.

    If your sketch is more recursive as the radius gets bigger (if (radius > 2)), and you constantly increase the size of your radius (drawCircle(width/2, height/2, i++/50))... then the sketch will constantly get more and more recursive, which calls the function more times, which takes longer, which slows it down.

  • Thank you!

  • You're calling drawCircle() recursively, twice on each iteration. After about 5 seconds, you've got a few thousand circles per draw cycle.

    This recursive approach works fine for static images, where you can control the depth of the recursion, but in this case where the initial radius (in the drawCircle call in draw() ) keeps increasing, it will eventually just crash.

    A better approach might be to maintain a dynamic array of objects (to some maximum number of objects) you want to draw. See, for example, ArrayList (https://processing.org/reference/ArrayList.html), or the ArrayListClass example under Examples->Topics->Advanced Data

Sign In or Register to comment.