如果我从文件中读取大字符串,那么JVM实际上会做什么? [英] What does JVM actually do if I read a large String from a file?
问题描述
这就是我的想法:
- JVM将字符串从文件系统复制到主内存中.
- JVM将字符串从主内存复制到Java堆中.
- 使用它.
我对吗?我的意思是,实际上有两步复制.
An I right ? I mean, there's actually two step copy.
推荐答案
vea可能有2个以上的副本.很大程度上取决于您的阅读方式.
veaThere could be more than 2 copies. Very much depends on how you are reading.
考虑包裹在BufferedReader中的FileReader的常见情况.
Consider the common case of a FileReader wrapped in a BufferedReader.
当您调用BufferedReader.readLine()时,您将获得三个副本.
When you call BufferedReader.readLine() you get three copies.
1)BufferedReader为空(开始),因此它在FileReader上调用read(char []).
1) The BufferedReader is empty (to start) so it call read(char[]) on the FileReader.
2)FileReader(在JVM的C层)对uint8 []缓冲区进行read()系统调用. (副本1)
2) The FileReader (at the C layer of the JVM) make a read() system call into a uint8[] buffer. (copy 1)
3)最好的情况是FileReader然后转换unit8 []的内容,并将结果复制到BufferedReader(副本2)提供的char []中. (请注意,即使我们有一个InputStreams并且结果是一个byte []而不是一个字符串,该副本仍然会存在.)
3) Best case FileReader then converts the unit8[] contents and copies the result into the char[] provided by the BufferedReader (copy 2). (Note this copy would still be present even if we have an InputStreams and the result was a byte[] instead of a string.)
4)然后,readLine()将char []复制到该行的末尾,并将其复制到String中. (副本3).
4) The readLine() then copies the char[] up to the end of the line into a String. (copy 3).
对于大多数事情,您不必担心所有复制.缓冲区很小,开销也很小.
For most things you don't need to worry about all of the copying. The buffers are small and the overhead is minimal.
Rob
这篇关于如果我从文件中读取大字符串,那么JVM实际上会做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!