gpt4 book ai didi

java - 我应该缓存 System.getProperty ("line.separator")吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:43:33 25 4
gpt4 key购买 nike

考虑这样的方法:

@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (final Room room : map)
{
sb.append(room.toString());
sb.append(System.getProperty("line.separator")); // THIS IS IMPORTANT
}
return sb.toString();
}

System.getProperty("line.separator") 可以多次调用。

我应该用 public final static String lineSeperator = System.getProperty("line.separator") 缓存这个值吗然后只使用 lineSeperator?

或者 System.getProperty("line.separator") 和使用静态字段一样快?

最佳答案

我认为您的问题提出了错误的二分法。我既不会每次都调用 getProperty,也不会为其声明一个静态字段。我只是将它提取到 toString 中的局部变量。

@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
final String newline = System.getProperty("line.separator");
for (final Room room : map) sb.append(room.toString()).append(newline);
return sb.toString();
}

顺便说一句,我已经对调用进行了基准测试。代码:

public class GetProperty
{
static char[] ary = new char[1];
@GenerateMicroBenchmark public void everyTime() {
for (int i = 0; i < 100_000; i++) ary[0] = System.getProperty("line.separator").charAt(0);
}
@GenerateMicroBenchmark public void cache() {
final char c = System.getProperty("line.separator").charAt(0);
for (int i = 0; i < 100_000; i++) ary[0] = (char)(c | ary[0]);
}
}

结果:

Benchmark                     Mode Thr    Cnt  Sec         Mean   Mean error    Units
GetProperty.cache thrpt 1 3 5 10.318 0.223 ops/msec
GetProperty.everyTime thrpt 1 3 5 0.055 0.000 ops/msec

缓存方法的速度提高了两个数量级以上。

请注意,getProperty 调用对所有字符串构建的总体影响非常非常小。

关于java - 我应该缓存 System.getProperty ("line.separator")吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18045391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com