How do I reduce lag for many operations?

edited December 2017 in Programming Questions

Hello, I am making a program with many particles that refer to each other and it is getting quite laggy. It is for every particle trying to calculate the distance to every other particle for gravity. So the more particles I add the lag increases exponentially. Any tips on how to reduce lag?



  • show your code, maybe you're doing it wrong

  • Because you have shown no code, I have no idea why every particle would need to calculate the distance to every other particle, but I assume it is because you want to check for collisions. If that is the case, you would not need to calculate the distance to a partice on the opposite site of the screen. But how does a particle know it's on the other side of the screen if it hasn't calculated the distance?

    One way is to divide the screen into squares and check the distance for every object in that square. that would decrease the amount of calculations per frame.

  • How many particles do you need?
    If hundreds you should be fine doing it the straightforward way with classes and PVectors.
    If thousands then you need very optimized "unreadable" code.

    int N = 500; // number of bodies
    class body {
      PVector position;
      PVector speed;
      float mass;
      body(float XPOS, float YPOS, float ZPOS, float XSPEED, float YSPEED, float MASS) {
        position = new PVector(XPOS, YPOS, ZPOS);
        speed = new PVector(XSPEED, YSPEED);
      void fall(float pointMass) {
        speed.add(PVector.mult(delta, pointMass*force));
      void fall2() {
        ellipse(position.x, position.y, 40, 40);
    ArrayList<body> bod = new ArrayList<body>();
    PVector delta;
    float force;
    float distance;
    body a;
    void setup() {
      size(500, 500); 
      for(int i=0;i<N;i++)
      bod.add(new body(random(400), random(400), 0, 0,0, random(10,40)) );
      delta = new PVector(0, 0);
      delta = PVector.sub(bod.get(0).position, bod.get(1).position);
    void draw() {
      for (int j=0; j<bod.size(); j++) {
        for (int i=j+1; i<bod.size(); i++) {
          delta = PVector.sub(bod.get(j).position, bod.get(i).position) ; 
          force = 1./delta.magSq()/delta.mag();
      for(body b:bod)b.fall2();
Sign In or Register to comment.