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

Ada*_*zyk 8 java optimization caching

考虑这样的方法:

@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();
}
Run Code Online (Sandbox Code Playgroud)

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

我应该缓存此值,public final static String lineSeperator = System.getProperty("line.separator") 以后再使用lineSeperator吗?

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

Mar*_*nik 3

我认为你的问题提出了错误的二分法。我既不会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();
}
Run Code Online (Sandbox Code Playgroud)

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

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]);
  }
}
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)

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

请注意,调用对所有字符串构建的总体影响getProperty非常非常不可能明显。