Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this method faster than Math.random()?

I am a beginner and have currently started working on a game for Android which uses a particle swarm optimization algorithm. I am now trying to optimize my code a little and i have quite a lot of Math.random() in for-loops which is running almost all the time. So i was thinking of a way to get around and skip all the Math.random() calls.

By using a method like this:

    float random[] = new float[100];
static int randomIndex=0;

private float myRandom(){
    if(randomIndex >= 99)
        randomIndex = 0;
    else
        randomIndex = randomIndex+1;
    return random[randomIndex];
}

...and also do this one time when the activity starts:

for (int i=0; i< 100; i++)
        random[i]=(float) Math.random();

My question is if this will be better (faster) than using Math.random()? Does anyone have a better suggestion how to do?

I also wonder if anyone know any good site where i can read more about how to write efficient java/android code. I'm afraid i kind of suck on it.

like image 697
Weldeborn Avatar asked Mar 13 '11 20:03

Weldeborn


1 Answers

Learn to trust the Java API: it's powerful and fast. "Premature optimization is the root of all evil." Make your program work before you start worrying about things such as this.

For your purpose however it might set your mind at ease to compare your method vs. Java's in a loop of say 30 million, then compare the times.

Not to mention filling an array of 100 random numbers then using it a million times is not random at all.

like image 130
Gunnar Hoffman Avatar answered Sep 21 '22 05:09

Gunnar Hoffman