假设如下:
String example = "something";
String firstLetter = "";
Run Code Online (Sandbox Code Playgroud)
是否存在差异,需要注意以下firstLetter可能影响绩效的分配方式; 哪个最好,为什么?
firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);
Run Code Online (Sandbox Code Playgroud)
第一个字母作为a返回的原因String是它在Hadoop中运行,并且需要分配给Text类型的字符串,firstLetter将作为a key从map()方法输出,例如:
public class FirstLetterMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
String line = new String();
Text firstLetter = new Text();
IntWritable wordLength = new IntWritable();
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
line = value.toString();
for (String word : line.split("\\W+")){
if …Run Code Online (Sandbox Code Playgroud) 我正在浏览String类API,看起来像substring方法导致潜在的内存泄漏,因为它与原始String共享相同的字符数组.
如果原始字符串很大,则子字符串返回的小字符串可以防止原始字符串(由大数组备份)从Java中的垃圾收集.
任何想法或我读错了API.