0

Java で、整数のテーブルを含むファイルを読み取るコードは次のとおりです。

public static int[][] getDataset() {

    // open data file to read n and m size parameters
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(filePath));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // count the number of lines
    int i = -1;
    String line = null, firstLine = null;
    do {

        // read line
        try {
            line = br.readLine();
            i++;
            if (i == 0) firstLine = line;
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

    } while (line != null);

    // close data file
    try {
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // check the data for emptiness
    if (i == 0) {
        System.out.println("The dataset is empty!");
        System.exit(1);
    }

    // initialize n and m (at least the first line exists)
    n = i; m = firstLine.split(" ").length;
    firstLine = null;

    // open data file to read the dataset
    br = null;
    try {
        br = new BufferedReader(new FileReader(filePath));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // initialize dataset
    int[][] X = new int[n][m];

    // process data
    i = -1;
    while (true) {

        // read line
        try {
            line = br.readLine();
            i++;
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // exit point
        if (line == null) break;

        // convert a line (string of integers) into a dataset row
        String[] stringList = line.split(" ");
        for (int j = 0; j < m; j++) {
            X[i][j] = Integer.parseInt(stringList[j]);
        }

    }

    // close data file
    try {
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    return X;

}

データセット サイズ パラメータnおよびmは、 タイプstatic final intであり、 と同様に外部で宣言されstatic final String filePathます。

私はあなたに私の解決策を提供し(おそらく初心者が後でこれを読むのに役立つでしょう)、時間を短縮したり、メモリの消費を減らしたりすることができるかどうか尋ねますか?私は完璧なマイクロ最適化に興味があります。ここでアドバイスをいただければ幸いです。特に、ファイルが 2 回開かれる方法が気に入りません。

4

1 に答える 1

0

ファイルを 1 回だけ読み取り、すべての行をArraList<String>. ArrayListgrows に自動的に追加します。後でその ArrayList を処理して行を分割します。

さらなる最適化: Strimg.split は巨大な正規表現アナライザーを使用します。StringTokenizer または独自の stringsplit メソッドで試してください。

ArrayList の代わりに、GrowingIntArray または GrowingStringArray を使用してオーバーヘッドを回避できます。これらはオーバーヘッドを回避しますが、あまり便利ではありません。

速度とメモリ使用量は矛盾しており、多くの場合、両方を最適化することはできません。

各列がオブジェクトであるため、Java 2d 配列ではより多くのスペースが必要です。X[col + 行 *rowsize] で 1 つの次元配列にアクセスします。

于 2013-03-08T12:21:21.677 に答える