我这里有这个代码来创建一个X空格字符串。
private static string GetWhiteSpaceString(int howManySpaces)
{
return new string(' ', howManySpaces);
}
我怎么能以某种方式缓存这个字符串,所以只有在空格数改变的情况下才会创建它?有没有比保留一些全局变量更好的方法?
谢谢:)
答案 0 :(得分:2)
我认为您不需要缓存String
。 .Net
可以很好地处理它。
但是,如果您仍想继续,为什么不创建一个Dictionary<int,string>
类型来存储生成的字符串并在返回新字符串之前查看它?
答案 1 :(得分: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
变化多少。
答案 2 :(得分:1)
创建字符串的方法可能不是缓存它们的最佳位置(如果有一个很好的理由来缓存它们)。使用字符串的代码可能有更多关于哪些字符串可以重用的信息。
如果缓存字符串,它们将是长寿命对象。这意味着它们可能会被移动到下一代内存堆中。将对象从一个堆移动到另一个堆意味着它将从内存中的一个位置复制到另一个堆,因此这至少与创建新字符串一样多。
在大多数情况下,创建新字符串而不是缓存它们会更有效。垃圾收集器专门用于有效处理短寿命物体。
答案 3 :(得分:0)
您可以创建静态(同步)Dictionary<int,string>
- 或者如果您将所有长度缓存到已知大小,只需string[]
(更快更简单;无需同步)。< / p>
例如:
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;
}
}