2011-01-05 29 views
1

我有这里的代码来创建一个X空格字符串。创建一个重复的字符串并缓存它?

private static string GetWhiteSpaceString(int howManySpaces) 
{ 
    return new string(' ', howManySpaces); 
} 

我怎么能以某种方式缓存这个字符串,所以它只能创建如果空格的数量改变例如?有没有比保留一些全局变量更好的方法?

谢谢:)

+2

如果你需要缓存它,这表明你正在创建这些的%^ tloads。为什么? – 2011-01-05 09:27:46

+5

“我们应该忘记小效率,大约97%的时间:过早优化是万恶之源” - Knuth – 2011-01-05 09:27:46

+0

请注意,如果数据是静态的,使这种方法*同步*非常重要;请参阅我的更新以获取更多信息 – 2011-01-05 10:38:43

回答

2

我不认为你需要缓存String.Net处理得很好。

但是,如果您仍想继续操作,为什么不创建Dictionary<int,string>类型来存储生成的字符串并在返回新字符串之前查看它?

0

您可以创建一个静态的(同步)Dictionary<int,string> - 或者,如果你正在缓存所有的长度达到一个已知的大小,只是一个string[](更快,更简单;无需同步其一)。

例如:

static readonly Dictionary<int, string> cache 
     = new Dictionary<int, string>(); 
    public static string GetSpaces(int count) { 
     // deal with brain-dead cases first to avoid lock for short strings 
     switch (count) 
     { // note these are all interned etc 
      case 0: return ""; 
      case 1: return " "; 
      case 2: return " "; 
      case 3: return " "; 
      case 4: return " "; 
      case 5: return "  "; 
      case 6: return "  "; 
      case 7: return "  "; 
      case 8: return "  "; 
      case 9: return "   "; 
      case 10: return "   "; 
     } 
     if(count < 0) throw new ArgumentOutOfRangeException("count"); 
     lock (cache) { 
      string s; 
      if (!cache.TryGetValue(count, out s)) { 
       cache.Add(count, s = new string(' ', count)); 
      } 
      return s; 
     } 
    } 
1

可能是这样的(仅在浏览器中编码,可能无法正常工作):

Dictionary<int, string> cache = new Dictionary<int, string>(); 
private static string GetWhiteSpaceString(int howManySpaces) 
{ 
    if(cache.Keys.Contains(howManySpaces)) 
    { 
     return cache[howManySpaces]; 
    } 
    else 
    { 
     var text = new string(' ', howManySpaces); 
     cache[howManySpaces] = text; 
     return text; 
    } 
} 

这可能会做你想要什么,但我很担心内存的使用。我想这取决于多少howManySpaces变化。

+0

如果将逻辑切换为使用'TryGet',则可以避免在项目存在时执行双重查找。 – 2011-01-05 09:39:11

1

创建字符串的方法可能不是缓存它们的最佳位置(如果甚至有足够的理由缓存它们)。使用字符串的代码可能包含有关哪些字符串可以重用的更多信息。

如果缓存字符串,它们将是长寿命的对象。这意味着他们可能会被移到下一代内存堆中。将一个对象从一个堆移动到另一个堆意味着它将从内存中的一个位置复制到另一个位置,所以这至少与创建新字符串一样重要。

在大多数情况下,创建新字符串而不是缓存它们会更有效。垃圾收集器特别用于高效地处理短暂的对象。

相关问题