CodeQL 文档

低效的 String 构造函数

ID: java/inefficient-string-constructor
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - efficiency
   - maintainability
Query suites:
   - java-security-and-quality.qls

单击以在 CodeQL 存储库中查看查询

String 类是不可变的,这意味着没有办法更改它表示的字符串。因此,很少需要复制 String 对象或基于现有字符串构造一个新实例,例如通过编写类似 String hello = new String("hello") 的内容。此外,此做法并不节省内存。

建议

复制的字符串在功能上与传递给 String 构造函数的参数没有区别,因此你可以简单地省略构造函数调用并直接使用传递给它的参数。除非需要显式复制参数字符串,否则这是一个安全的转换。

示例

以下示例展示了使用 String 构造函数复制字符串的三种情况,这效率低下。在每种情况下,只需删除构造函数调用 new String 并保留参数,即可生成更好的代码并减少内存消耗。

public void sayHello(String world) {
	// AVOID: Inefficient 'String' constructor
	String message = new String("hello ");

	// AVOID: Inefficient 'String' constructor
	message = new String(message + world);

	// AVOID: Inefficient 'String' constructor
	System.out.println(new String(message));
}

参考资料

  • J. Bloch,Effective Java(第二版),第 5 项。Addison-Wesley,2008 年。

  • Java API 规范:String(String)

  • ©GitHub, Inc.
  • 条款
  • 隐私