在Java中连接两个字符串的最快方法是什么? [英] What's the fastest way to concatenate two Strings in Java?

查看:130
本文介绍了在Java中连接两个字符串的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中连接两个字符串的最快方法是什么?

What's the fastest way to concatenate two Strings in Java?

ie

String ccyPair = ccy1 + ccy2;

我使用 cyPair 作为密钥在一个 HashMap 中,它在一个非常紧凑的循环中被调用以检索值。

I'm using cyPair as a key in a HashMap and it's called in a very tight loop to retrieve values.

当我描述然后这是瓶颈

java.lang.StringBuilder.append(StringBuilder.java:119)  
java.lang.StringBuilder.(StringBuilder.java:93)


推荐答案

这些例程之所以如此在基准测试中出现是因为这就是编译器如何实现你的+。

The reason why these routines show up in the benchmark is because that is how the compiler implements your "+" under the covers.

如果你真的需要连接字符串,你应该让编译器做它与+的魔力。如果您需要的是一个用于映射查找的键,一个包含具有合适的equals和hashMap实现的字符串的键类,可能是一个好主意,因为它避免了复制步骤。

If you really need the concatenated string, you should let the compiler do its magic with the "+". If you all need is a key for map lookup a key class holding both strings with suitable equals and hashMap implementations, might be a good idea as it avoids the copying step.

这篇关于在Java中连接两个字符串的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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