我应该缓存System.getProperty(" line.separator")吗? [英] Should I cache System.getProperty("line.separator")?

查看:106
本文介绍了我应该缓存System.getProperty(" line.separator")吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这样的方法:

@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)和使用静态字段一样快吗?

Or System.getProperty("line.separator") is as fast as using a static field?

推荐答案

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

I see your question as presenting a false dichotomy. I would neither call getProperty every time, nor declare a static field for it. I'd simply extract it to a local variable in 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();
}

BTW我已经对呼叫进行了基准测试。代码:

BTW I have benchmarked the call. The code:

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

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

The cached approach is more than two orders of magnitude faster.

请注意, getProperty 对所有字符串构建的整体影响非常非常不太明显。

Do note that the overall impact of getProperty call against all that string building is very, very unlikely to be noticeable.

这篇关于我应该缓存System.getProperty(&quot; line.separator&quot;)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆