字符串连接使用效率低下 [英] Inefficient use of string concatenation

查看:68
本文介绍了字符串连接使用效率低下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我突然在我的java-app(使用NetBeans作为IDE)中创建一个记录器时,突然看到一条警告:记录器中字符串连接使用效率不高".

I was creating a logger in my java-app (with NetBeans as IDE) when suddenly I saw a warning saying: "Inefficient use of string concatenation in logger".

我的原始代码是

srcLogger.getLogger().log(Level.INFO,"UploadBean.doUpload completado [" + file.getName() + "]\n");

但是NetBeans建议将其转换为模板(给出模板"在这里是什么意思?),并提供以下代码:

but NetBeans suggested to convert it to a template (what a "template" means here?) giving this code:

srcLogger.getLogger().log(Level.INFO, "UploadBean.doUpload completado [{0}]\n", file.getName());

这两种串联方式有什么区别,尽管我从未使用过后者.

What's the different between these two ways of concatenation, I never used the latter though.

干杯.

推荐答案

我将忽略该警告(如果可能,请将其关闭).串联的效率不是那么低,因为现代编译器将其替换为基于StringBuilder的高效实现(如果您查看类文件的字节码,就会看到它).

I'd ignore the warning (and switch if it off, if possible). The concatenation is not that inefficient, because modern compilers replace it with an efficient implementation based on StringBuilder (you'll see it if you look at the classfile's bytecode).

建议的替换方法不会串联字符串,但是需要一些额外的处理才能解析模板并将其与参数合并.

The suggested replacement doesn't concatenate Strings but it requires some extra processing to parse the template and merge it with the parameters.

Netbeans,这是一个坏建议.

Netbeans, that's a bad advice.

对于Java 1.5+而言,这是正确的. Java的较旧版本(可能)在串联过程中会创建许多未使用的String实例.

这篇关于字符串连接使用效率低下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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