【发布时间】:2021-03-14 05:42:41
【问题描述】:
我已经反编译了一个由第 3 方开发团队提供的修复程序。
这是原始代码:
if (this.getPassword() != null) {
this.uid = this.getUserName();
password = this.getPassword();
}
if (this.host != null) {
en.put("hostname", this.host);
if (password != null && password.toString().trim().length() != 0) {
en.put("password", password.toString());
}
if (this.uid != null && this.uid.trim().length() != 0) {
en.put("userID", this.uid);
}
}
这是解决方法:
if (this.getPassword() != null) {
this.uid = this.getUserName();
final char[] passwordTemp = this.getPassword();
password = new char[passwordTemp.length];
for (int i = 0; i < passwordTemp.length; ++i) {
password[i] = passwordTemp[i];
}
}
if (this.host != null) {
en.put("hostname", this.host);
if (password != null && password.toString().trim().length() != 0) {
en.put("password", new String(password));
}
if (this.uid != null && this.uid.trim().length() != 0) {
en.put("userID", this.uid);
}
}
这似乎大大降低了代码的性能。有谁知道为什么会这样做?有没有更好的方法来做到这一点?
【问题讨论】:
-
查看链接问题。他们使用
char[]而不是String作为密码。但是,它们的实现很差,因为密码稍后仍会转换为字符串:)) -
我假设
this.getPassword()返回的数组中的字符在某个时候被删除了,而在其他地方仍然需要它。因此他们将密码复制到另一个不会被破坏的数组中。 -
作为参考密码类型为:char[] password = null;
-
看了你的代码后,我不得不承认我很困惑。如果
password是char[],那么在它上面调用toString是毫无意义的,你不会得到数组中字符的字符串表示形式。 -
更改后您是否对应用程序进行了概要分析?瓶颈真的在您怀疑的代码 sn-p 中吗?我已经学会了关于性能问题的推测几乎总是失败的艰难方法。
标签: java string performance