如何使()循环花费更少的时间(android)?

时间:2013-03-16 21:03:53

标签: android optimization iteration

我正在为Android设备制作应用程序。我的应用程序中有一个函数,它有2个“for循环”,每个迭代3200次,访问53 KB .txt文件(包含3200行)并比较每行的字符串,每次迭代一行。 “for loops”还包含BufferedReader(),InputStreamReader(),InputStream()和StringTokenizer()。因此,当我在模拟器上运行应用程序时,它需要大约8秒来处理该功能。这是不可接受的。如何减少所需的时间,例如,半秒或最大值。 1秒?谢谢! 编辑:这是我的程序中有2个for循环的部分:

else if(a==2){
        String z="";
        try{
            InputStream is = getAssets().open("USCOUNTIES.txt");
            InputStreamReader iz=new InputStreamReader(is);
            BufferedReader bis = new BufferedReader(iz);

            int v=0;

            v=count("USCOUNTIES.txt");//counts number of lines in the .txt file
        //finding no. of counties to be displayed
            int counter=0;
            String pos;
            pos=Integer.toString(position);
            try{
            for(int i=0;i<v;i++){
                z=bis.readLine();
                //int x=pos.length();
                boolean a;
                //using stringtokenizer
                StringTokenizer st = new StringTokenizer(z, ","); 
                String substring;
                substring=(String) st.nextElement();
                a=substring.equals(pos);
                if(a==true){

                    counter=counter+1;

                }
            }}catch(Exception e){e.printStackTrace();}
            String array1[]=new String[counter];

            try{
                InputStream ig = getAssets().open("USCOUNTIES.txt");
                InputStreamReader ia=new InputStreamReader(ig);
                BufferedReader bos = new BufferedReader(ia);
            int j=0;
            for(int i=0;i<v;i++){
                z=bos.readLine();
                String[] split = z.split(",");
                if(split[0].equals(pos)){
                    array1[j]=split[1];
                    j=j+1;
                }

            }}
            catch(Exception e){e.printStackTrace();}

1 个答案:

答案 0 :(得分:1)

如果我是你,我只会解析一切,然后随心所欲地做任何事情。

这段代码就是这样做的,包括解析Integers(我怀疑你需要这些作为值,而不是Strings):

public void read() throws IOException {
    InputStream is = getAssets().open("USCOUNTIES.txt");
    InputStreamReader iz=new InputStreamReader(is);
    BufferedReader bis = new BufferedReader(iz);
    String line = "";
    String firstNumber = "";
    String secondNumber = "";
    String countyName = "";
    StringTokenizer st = null;
    HashMap<Pair, String> map = new HashMap<>();
    while((line = bis.readLine()) != null) {
        st = new StringTokenizer(line, ",");
        firstNumber = (String) st.nextElement();
        st = new StringTokenizer((String)st.nextElement(), ">");
        secondNumber = (String) st.nextElement();
        countyName = ((String) st.nextElement());
        countyName = countyName.substring(0, countyName.length()-1);
        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        map.put(new Pair(num1, num2), countyName);
    }
}

class Pair {
    int num1, num2;
    Pair(int num1, int num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

    public boolean equals(Object other) {
        if (other instanceof Pair) {
            Pair np = (Pair) other;
            return this.num1 == np.num1 && this.num2 == np.num2;
        }
        return false;
    }

    public int hashCode() {
        return (Integer.valueOf(num1).hashCode() >> 13) ^ Integer.valueOf(num2).hashCode();
    };
}

现在您只需使用以下行检索每个countyName

String s = map.get(new Pair(1,69));

然后返回Aleutians East

我希望能让你开始。

修改

这段代码使用2D SparseArray(非常像HashMap<Integer, Object>)。有了这个,一切都按第一个数字排序。

public class Reader {
    private String firstNumber = "";
    private String secondNumber = "";
    private String countyName = "";
    private StringTokenizer stringTokenizer = null;
    private SparseArray<SparseArray<String>> sparseArray = new SparseArray<SparseArray<String>>();
    private SparseArray<String> temporarySparseArray = null;

    public void readFromIS() throws IOException {
        InputStream is = getAssets().open("USCOUNTIES.txt");
        InputStreamReader iz=new InputStreamReader(is);
        BufferedReader bis = new BufferedReader(iz);
        String line = null;
        while((line = bis.readLine()) != null) {
            readLine(line);
        }
    }

    public void readFromList() {
        String[] strings = {
                "0,1>Autauga;",
                "0,2>Baldwin;",
                "0,3>Barbour;",
                "1,69>Aleutians East;",     
                "1,68>Aleutians West;"
        };
        for (String line : strings) {
            readLine(line);
        }
    }

    private void readLine(String line) {
        stringTokenizer = new StringTokenizer(line, ",");
        firstNumber = (String) stringTokenizer.nextElement();
        stringTokenizer = new StringTokenizer((String)stringTokenizer.nextElement(), ">");
        secondNumber = (String) stringTokenizer.nextElement();
        countyName = ((String) stringTokenizer.nextElement());
        countyName = countyName.substring(0, countyName.length()-1);
        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        if (sparseArray.get(num1) == null) {
            sparseArray.put(num1, new SparseArray<String>());
        }
        temporarySparseArray = sparseArray.get(num1);
        temporarySparseArray.put(num2, countyName);
        sparseArray.put(num1, temporarySparseArray);
        temporarySparseArray = null;
    }

    public void test() {
        readFromList();
        String s = sparseArray.get(0).get(2);
        SparseArray sa = sparseArray.get(0);
        System.out.println(sa.size()); //should be 3
        System.out.println(s); // should be Baldwin
    }
}

要检索所有以num1开头的县,比如0,你只需使用:

SparseArray<String> startingWithZero = sparseArray.get(0);

仅供参考:SparseArray HashMapintegers Integer,所以并非所有内容都必须自动生成(从intHashMap,您可以'将原始类型放在public void printEverythingStartingWithZero() { SparseArray<String> subSparseArray = sparseArray.get(0); //You first need a 1D sparseArray int key = 0; for(int i = 0; i < subSparseArray.size(); i++) { key = subSparseArray.keyAt(i); String county = subSparseArray.get(key); //county is the String in place (0,key) System.out.println(county); } } )中。

EDIT2 您打印1D sparseArray的地址。

sparseArray

您需要首先检索1D {{1}},前导零。