java - StringBuilder 中的多个 StringBuilder。值得吗?

标签 java string performance concatenation stringbuilder

我收到一份模型列表。模型的数量可能很大。这个模型有一堆属性,其中任何一个都可能是null

我需要根据模型的属性为每个模型构建一个字符串。如果 property == null,那么我会在结果字符串中添加一些静态部分,例如 "property1 is null"

如果 else property != null 然后我添加类似这样的内容 "property1 == 'valueOfThePropertyHere'"

结果字符串应该是这样的: prop1 == 'value1' and prop2 is null and prop3 == 'value3' and prop4 == 'value4' and prop5 is null and ..... propN == 'valueN'

然后我为列表中的每个模型生成这样的字符串。

显然,我在 for 循环中执行此操作,为此我使用 StringBuilder。问题是,在 StringBuilder 的 append 方法中,我使用三元运算符检查模型的每个字段是否为空,并基于此将此检查的结果添加到结果字符串中。但是如果一个属性不为 null 那么我需要添加一些静态部分 + 字段本身的值 + 一些更多的静态内容。这意味着我需要为我拥有的每个属性再添加一个 StringBuilder。或者我可以使用“+”,它无论如何都会被转换成 StringBuilder,据我所知,在 StringBuilder 中使用“+”是一种不好的做法(但我无论如何都必须使用它)。

例子:

List<Model> models = repository.getModels();

for (Model m: models) {
    StringBuilder stringBuilder = new StringBuilder();

    stringBuilder
    .append(m.getField1() == null ? "field1  is null" : "field1 == '" + new StringBuiler().append(m.getField1()).append("'").append(" and ").toString()))
    .append(m.getField2() == null ? "field2  is null" : "field2 == '" + new StringBuiler().append(m.getField2()).append("'").append(" and ").toString()))
    ...............
    .append(m.getFieldN() == null ? "fieldN  is null" : "fieldN == '" + new StringBuiler().append(m.getFieldN()).append("'").append(" and ").toString()));

    System.out.println(stringBuilder.toString());
    }

在我看来,从性能的角度来看,它看起来不太好,因为对于模型列表中的每个模型,我都在堆中创建了另一组 StringBuilder 对象,只是为了获取结果字符串。

我错过了什么吗?从性能的角度来看,是否有更好的方法来做到这一点?或者没关系,因为我现在看不到其他选项。

最佳答案

追求简单。

代替

stringBuilder
.append(m.getField1() == null ? "field1  is null" : "field1 == '" + new StringBuiler().append(m.getField1()).append("'").append(" and ").toString()))

使用:

if (m.getField1() == null) {
  stringBuilder.append("field1  is null");
} else {
  stringBuilder.append("field1 == '").append(m.getField1()).append("'").append(" and ");
}

除了在 StringBuilder.append 调用中使用 StringBuilder 的明显奇怪之外(为什么不直接使用 + 呢... ),真的很难解析 : 在条件表达式中的位置。将它分成几行要容易得多。


如果您发现自己不得不多次重复此代码模式,请定义一个方法:

void append(StringBuilder stringBuilder, String name, Object value) {
  stringBuilder.append(name);
  if (value == null) {
    stringBuilder.append(" is null");
  } else {
    stringBuilder.append(" == '").append(value).append("'").append(" and ");
  }
}

然后像这样调用:

append(stringBuilder, "field1", m.getField1());
append(stringBuilder, "field2", m.getField2());
append(stringBuilder, "field3", m.getField3());

关于java - StringBuilder 中的多个 StringBuilder。值得吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768828/

相关文章:

java - 如何将忙碌光标添加到应用程序中的每个事件

java - 人脸流不适用于@Named

javascript - 小写/大写字符串比较问题

javascript - 计算字符串javascript中的单词出现次数

c# - 我正在尝试使用 linq 简化一个语句,该语句采用 2 个数字列表并从第二个数字中减去第一个数字

java - 无法通过 spring 配置从 jar 检索类路径中的私钥 - jar 内的文件对 spring 不可见

java - 如何定位这个java while循环?

ruby - 除第一个字符外的小写单词

python - 磁盘寻道时间测量方法

performance - 通过减少 for 循环数量来加速