Here is a way to measure the difference:
Code:static final int numero_agentes = 600;
static final int BALL_SIZE = 20;
long totalTime;
ball[] bolas = new ball[numero_agentes];
void setup(){
size(400,400);
for(int i = 0; i<numero_agentes; i++){
bolas[i] = new ball(i);
}
}
void draw(){
background(250, 250, 0);
for(int i = 0; i<numero_agentes; i++){
bolas[i].collision(i);
bolas[i].dibuja();
bolas[i].mueve();
}
if (frameCount > 1000)
{
println("Total: " + totalTime);
exit();
}
}
class ball {
float x = random(200);
float y = random(300);
float colorr = 70;
int rank;
float distancia;
boolean collided ;
ball(int i) {
rank = i;
}
void dibuja() {
if (collided)
{
colorr = 0;
collided = false;}
else
colorr = 250;
fill(colorr);
ellipse(x, y , BALL_SIZE, BALL_SIZE);
}
void mueve(){
x = x + random(2) - 1;
y = y + random(2) - 1;
}
void collision(int start){
long t = millis();
//collided = false;
for(int i = start + 1; i < numero_agentes ; i++){
if(bolas[i] != this) {
distancia = dist(x, y , bolas[i].x, bolas[i].y) ;
if (distancia < BALL_SIZE ) {
collided = true;
bolas[i].collided = true;
}
}
}
totalTime += millis() - t;
}
}
.
Second, naive code: 7141, 6711, 6983
First code: 3752, 3528, 3817
My code: 3518, 3697, 3370
The last optimization (using constants) isn't really significant...
Note I do (at least) three runs, because of system activity.
The visual difference isn't great, but with much more particles, it might be significant.
There is another well known optimization: avoid the square root calculation done in dist().
Code: void collision(int start){
long t = millis();
//collided = false;
for(int i = start + 1; i < numero_agentes ; i++){
if(bolas[i] != this) {
distancia = (x - bolas[i].x)*(x - bolas[i].x) + (y - bolas[i].y)*(y - bolas[i].y);
if (distancia < BALL_SIZE*BALL_SIZE ) {
collided = true;
bolas[i].collided = true;
}
}
}
totalTime += millis() - t;
}
Results: 1819, 1751, 2221