我知道它应该只是谷歌,但也许你们可以在某个时候救我。
我尝试在我的Android应用程序中运行日志进程,并且在某段时间后我得到了一个内存不足的例子。
我想知道为什么会这样?
class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
int factor = 59;
int factorSuperNum = 35;
int num;
List<Integer> alreadyIn = new ArrayList<Integer>();
StringBuilder sb = new StringBuilder();
for (int j=0; j<5000000; j++){
alreadyIn.clear();
for(int i=0;i<5;i++){
num = (int) (1 + (Math.random() * factor) % factor);
while (alreadyIn.contains(num))
num = (int) (1 + (Math.random() * factor) % factor);
alreadyIn.add(num);
}
if(j % 100000 == 0)
Log.i("SendEmail", j + "" );
num = (int) (1 + (Math.random() * factorSuperNum) % factorSuperNum);
alreadyIn.add(num);
for (int finalNum : alreadyIn) {
sb.append(finalNum + " ");
}
sb.append("\n");
}
return null;
}
}
答案 0 :(得分:1)
这个代码在很多情况下很糟糕......
首先(Math.random() * factor) % factor
为什么你要随机乘以因子?你知道random % x
不好吗?
第二个OOME是因为你在每次迭代中都会向StringBuilder添加一行,所以在5M迭代后它需要至少10MB(5M * 20-40bytes)
thrid从因子中取5,你可以使用范围从1到因子的ArrayList并将其洗牌并取第5个元素:
import java.util.*;
import java.lang.*;
import java.io.*;
class LOLOLOLOLOL
{
static final int F = 59;
static final int FSN = 35;
static final ArrayList<Integer> range1toF = new ArrayList<Integer>();
static final Random rnd = new Random();
static{
for(int i = 1; i < F; i++)
range1toF.add(i);
}
public static void main (String[] args) throws java.lang.Exception
{
final PrintStream ps = new PrintStream(System.out); //or from File
for(int i = 0; i < 20; i++){
Collections.shuffle(range1toF, rnd);
for(int j = 0; j< 5; j++){
ps.print(range1toF.get(j));
ps.print(", ");
}
ps.println(rnd.nextInt(FSN - 1) + 1);
}
}
}