简体   繁体   English

哪个使用较少的内存String.format或+ / StringBuilder?

[英]Which uses less memory String.format or +/StringBuilder?

I've been searching through SO for awhile and all I can find is references to speed for strings and one or two rather misguided attempts at memory benchmarking. 我已经在SO中搜索了一段时间,我所能找到的只是对字符串速度的引用以及一次或两次在内存基准测试中误导的尝试。

My situation is that we have a ton of logging messages in our application and we're wondering if there is any measurable MEMORY advantage to using String.format vs. + vs. StringBuilder. 我的情况是我们的应用程序中有大量日志消息,我们想知道使用String.format与+ vs. StringBuilder是否有可衡量的MEMORY优势。

I've got a solid grip on measuring the time each of these is taking and there are plenty of SO posts for that. 我在衡量每个项目所花费的时间方面拥有扎实的实力,为此,有很多SO职位。

Can anyone tell me which one is better for lowering memory consumption? 谁能告诉我哪种方法可以降低内存消耗?

Example: 例:

if(LOG.isDebugEnabled()) LOG.debug(String.format("Invoice id = %s is waiting for processing", invoice.getId()));

Since String.format() is much more complicated because it supports format sequences and data types (%s, %d etc) it is expected to be more performance and memory expensive. 由于String.format()由于支持格式序列和数据类型(%s,%d等String.format()而变得更加复杂,因此,它的性能和内存消耗将更高。 However I believe this may be significant for very long strings only. 但是,我认为这可能仅对很长的字符串有意义。

I believe String.format would use less memory. 我相信String.format将使用更少的内存。 When using StringBuilder, you need to create a new builder object and then append string to it. 使用StringBuilder时,需要创建一个新的构建器对象,然后将字符串追加到该对象。 The creation of the object and the constant references to it (via append or similar methods) would seem to me to be more memory intensive than to return a straight forward string using String.format. 在我看来,对象的创建和对其的常量引用(通过append或类似方法)比使用String.format返回简单的字符串要占用更多的内存。

StringBuilder uses a temporary object before creating the final string. 在创建最终字符串之前,StringBuilder使用一个临时对象。 String.format seems like a more direct way and therefore less memory intensive. String.format似乎是一种更直接的方法,因此占用的内存更少。 Moreover, StringBuilder asks for a specific size when initialized (or else it will default to some value). 而且,StringBuilder在初始化时会要求特定的大小(否则它将默认为某个值)。 You could compare the default allocated memory values of a StringBuilder object versus a plain old String object. 您可以将StringBuilder对象的默认分配内存值与普通的旧String对象进行比较。

You could test these two options with a large dataset of strings to be built and assessing the time it takes for each approach. 您可以使用要构建的大型字符串数据集测试这两个选项,并评估每种方法所需的时间。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM