本文介绍了字符串连接需要多少个存储位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行字符串连接需要多少个存储位置?

How many memory locations will it take to have a string concatenation?

String myStringVariable = "Hello";

在以下两个语句中:

String s = "ABC" + "Hello" + "DEF";

String s = "ABC";
s = s + "Hello";
s = s + "DEF";

String s = "ABC" + myStringVariable + "DEF";

哪个会消耗更多的内存?在哪种情况下,StringBuilder最有用?

Which will consume more memory? In which of the case StringBuilder is useful to the most?

推荐答案

第一个语句将由编译器转换为String s = "ABCDEF";,因此不会出现任何隐含

First statement will be converted by compiler into String s = "ABCDEF"; so there will be no concatination

第二条语句将由编译器转换为以下代码(或类似的代码)

Second statement will be converted by compiler into this code (or something like this)

    String s = "ABC";
    StringBuilder sb = new StringBuilder(s);
    sb.append("DEF");
    s = sb.toString();

这篇关于字符串连接需要多少个存储位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 16:17