开发者

Java data type problem

I am working with matrix in java. ( another story :) )

I want to read a CSV file and store it in a variable. I will manipulate values then again store it in CSV file. I used STRING as data type. But if CSV file has like 500 columns. It kill my program speed :(. I think this is not good data type. Which data type I can use to temporary store LONG TEXT?

If my question is not clear please ask questions. I will explain. Thanks

P.S: I am reading one line and storing it in variable like this

String str;

str += read line by line from CSV;

here is the loop

String reduceM="";

 for(int kk=0;kk<W2.getRowDimension();kk++){
     for(int jj=0;jj<W2.getColumnD开发者_开发知识库imension();jj++){
         reduceM += Double.toString(reduceMatrix[kk][jj]);
     }
     System.out.println("\r\n");
 }


Use a StringBuilder (or StringBuffer if you're using Java 1.5 or older):

StringBuilder builder = new StringBuilder();
for (int kk = 0; kk<W2.getRowDimension(); kk++) {
    for(int jj = 0; jj < W2.getColumnDimension(); jj++) {
        builder.append(reduceMatrix[kk][jj]);
    }
}

This will avoid it creating a new (and increasingly long) string for each iteration of the two loops.

However, there are no commas or line-breaks in this code - I suspect you actually want something like this:

StringBuilder builder = new StringBuilder();
for (int kk = 0; kk < W2.getRowDimension(); kk++) {
    for (int jj = 0; jj < W2.getColumnDimension(); jj++) {
        builder.append(reduceMatrix[kk][jj])
               .append(",");
    }
    builder.append("\n"); // Or whatever line terminator you want
}

Note that that will leave an extra comma at the end of each row - let me know if you want ideas of how to remove that.

See this article for why this could make a huge improvement to your running time. (Note that it's an old article, talking about StringBuffer rather than StringBuilder - the latter is just an unsynchronized version of the former.)


Use the 'StringBuffer' class for concatenations. It is much more efficient.

Take a look at this article for an explanation: here

EDIT - Sorry I did not see this was already answered


Prefer StringBuilder, there is a big difference in performance compared to the string concatenation(+).


In addition to the skeet's great answer; dont write to system.out if its not necessary, or if you want to write to console use buffers or write when loop finishes. It makes your program cumbersome because each time it is encountered in the loop System.out stream opens writes flushes and closes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜