[英]Is casting an expensive operation?
Scenario : 场景 :
Should I : 我应该 :
I will have to keep the things simple . 我必须保持简单。 Any suggestions ?
有什么建议 ?
Casting doesn't change the amount of memory an object occupies. 强制转换不会更改对象占用的内存量。 It just changes the runtime type.
它只是改变了运行时类型。
If you can do those operations on a per-row basis, then just do the operation immediately inside the loop wherein you read a single line. 如果您可以按行进行这些操作,那么只需在循环内执行操作即可读取单行。
while ((line = reader.readLine()) != null) {
line = process(line);
writer.println(line);
}
This way you effectively end up with only a single line in Java's memory everytime instead of the whole file. 这样,您每次只能在Java内存中只有一行而不是整个文件。
Or if you need to do those operations based on the entire CSV file (ie, those operations are dependent on all rows), then your most efficient bet is to import the CSV file in a real SQL database and then use SQL statements to alter the data and then export it to CSV file again. 或者,如果您需要基于整个CSV文件执行这些操作(即,这些操作依赖于所有行),那么最有效的方法是将CSV文件导入真实的SQL数据库,然后使用SQL语句来更改数据,然后再次将其导出为CSV文件。
I'd recommend using a MappedByteBuffer (from NIO), that you can use to read a file too big to fit into memory. 我建议使用MappedByteBuffer(来自NIO),您可以使用它来读取太大而无法放入内存的文件。 It maps only a region of the file into memory;
它只将文件的一个区域映射到内存中; once you're done reading this region (say, the first 10k), map the next one, and so on, until you've read the whole file.
一旦你读完这个区域(比如说,前10k),就要映射下一个区域,依此类推,直到你读完整个文件。 Memory-efficient and quite easy to implement.
内存效率高,易于实现。
Java Casts: like Java Casts:喜欢
Object a = new String();
String b (String) a;
are not expensive. 不贵。 -- No matter if you cast Strings or any other type.
- 无论你是否施放弦乐或任何其他类型。
Your real value add will be to read each line as a String, which is pretty easy in Java. 您真正的增值将是将每行读取为String,这在Java中非常简单。 After it's in a String, it is trivial to split the string on each comma with
在它的字符串之后,在每个逗号上拆分字符串是微不足道的
String[] row = parsedRow.split(",");
The you will have a String for each value in the array, which can then be operated on. 对于数组中的每个值,您将拥有一个String,然后可以对其进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.