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

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

问题描述

我正在我的 java 应用程序中创建一个记录器(使用 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() + "]
");

但 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}]
", 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天全站免登陆