这个方法比Math.random()快吗? [英] Is this method faster than Math.random()?
问题描述
我是一个初学者,目前已经开始研究使用粒子群优化算法的Android游戏.我现在正在尝试稍微优化我的代码,并且在for循环中有很多Math.random(),它几乎一直在运行.因此,我正在考虑一种解决方法,并跳过所有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();
我的问题是,这是否比使用Math.random()更好(更快)?有谁有更好的建议怎么做?
My question is if this will be better (faster) than using Math.random()? Does anyone have a better suggestion how to do?
我还想知道是否有人知道任何好的网站,在这里我可以阅读更多有关如何编写有效的Java/Android代码的信息.恐怕我很烂.
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.
推荐答案
学习信任Java API:它功能强大且快速. 过早的优化是万恶之源."在开始担心诸如此类的事情之前,请使您的程序正常工作.
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.
但是,出于您的目的,您可以轻松地将自己的方法与Java的方法(例如3000万个循环)进行比较,然后比较时间.
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.
更不用说填充100个随机数的数组,然后使用它一百万次根本不是随机的.
Not to mention filling an array of 100 random numbers then using it a million times is not random at all.
这篇关于这个方法比Math.random()快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!