为什么这段代码将流存储到字符串对象中要花很长时间? [英] why this code to store out put of stream to string object is taken long time?

查看:131
本文介绍了为什么这段代码将流存储到字符串对象中要花很长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FileInputStream in = new FileInputStream("C:\\Users\\User_2\\Pictures\\19082012122.jpg");
           
           int c;
           String s = "";
           while((c = in.read()) != -1)
               s += c + " ";

推荐答案

jpg文件是二进制文件,但如果不是,则可以使用StringBuilder [ ^ ]

将String用作输入的缓冲区效率低下,string实际上并不意味着这样做.

您应该确定文件的大小(以字节为单位),并使用byte[]数组和
A jpg file is a binary file, but if it wasn''t you could use a StringBuilder[^]

Using String as a buffer for the input is inefficient, string really isn''t meant for this.

You should determine the size of the file in bytes and use a byte[] array with the read[^] method.

Best regards
Espen Harlinn


在Java中,所有String实例都是不可变的.这意味着一旦创建它们,便无法更改其内容.因此,您的s += c + " ";语句执行以下操作:创建一个新的String对象,其值是原始字符串c" "串联在一起,然后将此新字符串分配给s变量. s不再引用旧字符串,因此在某些时候将被垃圾回收.根据Java编译器的优化能力,在创建新值s之前,old_s + c + " "表达式可能会使用其他临时字符串,因为它首先添加old_s + c(这是临时字符串),然后添加" "到临时字符串.如果使用StringBuilder,则它具有内部存储,可让您更有效地处理字符串数据,并且可以随时根据其实际内容创建String实例.如果不必,请不要使用StringBuffer而不是StringBuilder,因为前者包含线程同步,所以它慢得多!除此之外,永远不要将二进制数据存储在字符串中!
In java all String instances are immutable. This means that once you created them you can not change their contents. Because of this your s += c + " "; statement does the following: Creates a new String object whose value is the the original string, c, and " " concatenated together then assign this new string to the s variable. s no longer references the old string so that will be garbage collected at some point. Depending on the optimization capabilities of the java compiler the old_s + c + " " expression might use an additional temporary string before creating the new value of s because first it adds old_s + c (this is the temp string), then it adds " " to the temp string. If you use StringBuilder it has an internal storage that allows you to manipulate your string data much more efficiently and you can create a String instance from its actual content at any point. Don''t use StringBuffer instead of StringBuilder if you dont have to because the former contains thread synchronization so it is much slower! Apart from this, you should never store binary data in a string!


这篇关于为什么这段代码将流存储到字符串对象中要花很长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆