11

我有一个大文件,它本质上包含如下数据:

Netherlands,Noord-holland,Amsterdam,FooStreet,1,...,...
Netherlands,Noord-holland,Amsterdam,FooStreet,2,...,...
Netherlands,Noord-holland,Amsterdam,FooStreet,3,...,...
Netherlands,Noord-holland,Amsterdam,FooStreet,4,...,...
Netherlands,Noord-holland,Amsterdam,FooStreet,5,...,...
Netherlands,Noord-holland,Amsterdam,BarRoad,1,...,...
Netherlands,Noord-holland,Amsterdam,BarRoad,2,...,...
Netherlands,Noord-holland,Amsterdam,BarRoad,3,...,...
Netherlands,Noord-holland,Amsterdam,BarRoad,4,...,...
Netherlands,Noord-holland,Amstelveen,BazDrive,1,...,...
Netherlands,Noord-holland,Amstelveen,BazDrive,2,...,...
Netherlands,Noord-holland,Amstelveen,BazDrive,3,...,...
Netherlands,Zuid-holland,Rotterdam,LoremAve,1,...,...
Netherlands,Zuid-holland,Rotterdam,LoremAve,2,...,...
Netherlands,Zuid-holland,Rotterdam,LoremAve,3,...,...
...

这是一个数千兆字节的文件。我有一个类可以读取此文件并将这些行(记录)公开为IEnumerable<MyObject>. 这MyObject有几个属性(Country, Province, City, ...)等。

如您所见,存在大量重复数据。我想继续将基础数据公开为IEnumerable<MyObject>. 但是,其他一些类可能(并且可能会)对这些数据进行一些分层视图/结构,例如:

Netherlands
    Noord-holland
        Amsterdam
            FooStreet [1, 2, 3, 4, 5]
            BarRoad [1, 2, 3, 4]
            ...
        Amstelveen
            BazDrive [1, 2, 3]
            ...
         ...
    Zuid-holland
        Rotterdam
            LoremAve [1, 2, 3]
            ...
        ...
    ...
...

在阅读这个文件时,我基本上是这样做的:

foreach (line in myfile) {
    fields = line.split(",");
    yield return new MyObject {
        Country = fields[0],
        Province = fields[1],
        City = fields[2],
        Street = fields[3],
        //...other fields
    };
}

现在,对于手头的实际问题:我可以用来string.Intern()实习国家、省、城市和街道字符串(这些是主要的“恶棍”,MyObject还有其他几个与问题无关的属性)。

foreach (line in myfile) {
    fields = line.split(",");
    yield return new MyObject {
        Country = string.Intern(fields[0]),
        Province = string.Intern(fields[1]),
        City = string.Intern(fields[2]),
        Street = string.Intern(fields[3]),
        //...other fields
    };
}

当将整个数据集保存在内存中时,这将节省大约 42% 的内存(经过测试和测量),因为所有重复的字符串都是对同一字符串的引用。此外,当使用大量 LINQ.ToDictionary()方法创建层次结构时,相应的键(国家、省等)。字典会更有效率。

然而,使用的缺点之一(除了性能的轻微损失,这不是问题)string.Intern()是字符串将不再被垃圾收集。但是当我处理完我的数据后,我确实希望(最终)收集所有垃圾。

可以使用 aDictionary<string, string>来“实习”这些数据,但我不喜欢拥有 a 的“开销” keyvalue实际上我只对key. 我可以设置valuetonull或使用与 value 相同的字符串(这将导致keyand中的引用相同value)。这只是几个字节的小代价,但它仍然是一个代价。

像 a 这样的东西HashSet<string>对我来说更有意义。但是,我无法获得对 HashSet 中字符串的引用;我可以查看 HashSet 是否包含特定字符串,但无法获得对 HashSet 中已定位字符串的特定实例的引用。我可以为此实现我自己HashSet的,但我想知道您的 StackOverflowers 可能会提出哪些其他解决方案。

要求:

  • 我的“FileReader”类需要不断暴露IEnumerable<MyObject>
  • 我的“FileReader”类可能会做一些事情(比如string.Intern())来优化内存使用
  • MyObject班级不能改变;我不会创建一个City类、Country类等并将它们MyObject公开为属性而不是简单的string属性
  • Country目标是通过对,Province等中的大部分重复字符串进行去重来提高内存效率City;这是如何实现的(例如字符串实习、内部哈希集/集合/某些东西的结构)并不重要。然而:
  • 我知道我可以将数据填充到数据库中,或者在这个方向上使用其他解决方案;我对这类解决方案不感兴趣。
  • 速度只是次要的问题;当然越快越好,但是在读取/迭代对象时性能(轻微)损失是没有问题的
  • 由于这是一个长时间运行的进程(如:运行 24/7/365 的 Windows 服务),偶尔会处理大量此类数据,我希望在完成后对数据进行垃圾收集;字符串实习效果很好,但从长远来看,会导致一个巨大的字符串池,其中包含大量未使用的数据
  • 我希望任何解决方案都“简单”;用 P/Invokes 和内联汇编(夸张)添加 15 个类是不值得的。代码可维护性在我的列表中很重要。

这更像是一个“理论”问题。我问这纯粹是出于好奇/兴趣。没有“真正的”问题,但我可以看到,在类似的情况下,这对某人来说可能是个问题。


例如:我可以这样做:

public class StringInterningObject
{
    private HashSet<string> _items;

    public StringInterningObject()
    {
        _items = new HashSet<string>();
    }

    public string Add(string value)
    {
        if (_items.Add(value))
            return value;  //New item added; return value since it wasn't in the HashSet
        //MEH... this will quickly go O(n)
        return _items.First(i => i.Equals(value)); //Find (and return) actual item from the HashSet and return it
    }
}

但是对于大量(要重复数据删除的)字符串,这将很快陷入困境。我可以查看HashSetDictionary的参考源,或者...并构建一个类似的类,该类不返回该Add()方法的 bool,而是在内部/存储桶中找到的实际字符串。

到目前为止,我能想到的最好的方法是:

public class StringInterningObject
{
    private ConcurrentDictionary<string, string> _items;

    public StringInterningObject()
    {
        _items = new ConcurrentDictionary<string, string>();
    }

    public string Add(string value)
    {
        return _items.AddOrUpdate(value, value, (v, i) => i);
    }
}

在我实际上只对密钥感兴趣的情况下,具有密钥和值的“惩罚”。虽然只有几个字节,但付出的代价很小。巧合的是,这也减少了 42% 的内存使用量;string.Intern()与使用产量时的结果相同。

tolanj 提出了 System.Xml.NameTable

public class StringInterningObject
{
    private System.Xml.NameTable nt = new System.Xml.NameTable();

    public string Add(string value)
    {
        return nt.Add(value);
    }
}

(我删除了锁和 string.Empty 检查(后者因为 NameTable已经这样做了))

xanatos 提出了一个 CachingEqualityComparer

public class StringInterningObject
{
    private class CachingEqualityComparer<T> : IEqualityComparer<T> where T : class
    {
        public System.WeakReference X { get; private set; }
        public System.WeakReference Y { get; private set; }

        private readonly IEqualityComparer<T> Comparer;

        public CachingEqualityComparer()
        {
            Comparer = EqualityComparer<T>.Default;
        }

        public CachingEqualityComparer(IEqualityComparer<T> comparer)
        {
            Comparer = comparer;
        }

        public bool Equals(T x, T y)
        {
            bool result = Comparer.Equals(x, y);

            if (result)
            {
                X = new System.WeakReference(x);
                Y = new System.WeakReference(y);
            }

            return result;
        }

        public int GetHashCode(T obj)
        {
            return Comparer.GetHashCode(obj);
        }

        public T Other(T one)
        {
            if (object.ReferenceEquals(one, null))
            {
                return null;
            }

            object x = X.Target;
            object y = Y.Target;

            if (x != null && y != null)
            {
                if (object.ReferenceEquals(one, x))
                {
                    return (T)y;
                }
                else if (object.ReferenceEquals(one, y))
                {
                    return (T)x;
                }
            }

            return one;
        }
    }

    private CachingEqualityComparer<string> _cmp; 
    private HashSet<string> _hs;

    public StringInterningObject()
    {
        _cmp = new CachingEqualityComparer<string>();
        _hs = new HashSet<string>(_cmp);
    }

    public string Add(string item)
    {
        if (!_hs.Add(item))
            item = _cmp.Other(item);
        return item;
    }
}

(稍作修改以“适合”我的“Add() 接口”)

根据Henk Holterman 的要求

public class StringInterningObject
{
    private Dictionary<string, string> _items;

    public StringInterningObject()
    {
        _items = new Dictionary<string, string>();
    }

    public string Add(string value)
    {
        string result;
        if (!_items.TryGetValue(value, out result))
        {
            _items.Add(value, value);
            return value;
        }
        return result;
    }
}

我只是想知道是否有一种更整洁/更好/更酷的方式来“解决”我的(不是实际的)问题。到目前为止,我想我有足够的选择眨眼


以下是我为一些简单、简短、初步的测试得出的一些数字:


非优化
内存:~4,5Gb
加载时间:~52s


StringInterningObject(见上文,ConcurrentDictionary变体)
内存:~2,6Gb
加载时间:~49s


string.Intern()
内存:~2,3Gb
加载时间:~45s


System.Xml.NameTable
内存:~2,3Gb
加载时间:~41s


CachingEqualityComparer
内存:~2,3Gb
加载时间:~


Dictionary根据Henk Holterman 的要求, StringInterningObject(见上文,(非并发)变体) :
内存:~2,3Gb
加载时间: ~39s

尽管数字不是很确定,但似乎非优化版本的许多内存分配实际上比使用任何一个string.Intern()或上面StringInterningObject的 s 都慢得多,这会导致(稍微)更长的加载时间。此外,string.Intern()似乎“赢”了,StringInterningObject但幅度不大;<< 查看更新。

4

3 回答 3

3

当有疑问时,作弊!:-)

public class CachingEqualityComparer<T> : IEqualityComparer<T> where  T : class
{
    public T X { get; private set; }
    public T Y { get; private set; }

    public IEqualityComparer<T> DefaultComparer = EqualityComparer<T>.Default;

    public bool Equals(T x, T y)
    {
        bool result = DefaultComparer.Equals(x, y);

        if (result)
        {
            X = x;
            Y = y;
        }

        return result;
    }

    public int GetHashCode(T obj)
    {
        return DefaultComparer.GetHashCode(obj);
    }

    public T Other(T one)
    {
        if (object.ReferenceEquals(one, X))
        {
            return Y;
        }

        if (object.ReferenceEquals(one, Y))
        {
            return X;
        }

        throw new ArgumentException("one");
    }

    public void Reset()
    {
        X = default(T);
        Y = default(T);
    }
}

使用示例:

var comparer = new CachingEqualityComparer<string>();
var hs = new HashSet<string>(comparer);

string str = "Hello";

string st1 = str.Substring(2);
hs.Add(st1);

string st2 = str.Substring(2);

// st1 and st2 are distinct strings!
if (object.ReferenceEquals(st1, st2))
{
    throw new Exception();
}

comparer.Reset();

if (hs.Contains(st2))
{
    string cached = comparer.Other(st2);
    Console.WriteLine("Found!");

    // cached is st1
    if (!object.ReferenceEquals(cached, st1))
    {
        throw new Exception();
    }
}

我创建了一个相等比较器,它“缓存”Equal它分析的最后一个术语:-)

然后一切都可以封装在一个子类中HashSet<T>

/// <summary>
/// An HashSet&lt;T;gt; that, thorough a clever use of an internal
/// comparer, can have a AddOrGet and a TryGet
/// </summary>
/// <typeparam name="T"></typeparam>
public class HashSetEx<T> : HashSet<T> where T : class
{

    public HashSetEx()
        : base(new CachingEqualityComparer<T>())
    {
    }

    public HashSetEx(IEqualityComparer<T> comparer)
        : base(new CachingEqualityComparer<T>(comparer))
    {
    }

    public T AddOrGet(T item)
    {
        if (!Add(item))
        {
            var comparer = (CachingEqualityComparer<T>)Comparer;

            item = comparer.Other(item);
        }

        return item;
    }

    public bool TryGet(T item, out T item2)
    {
        if (Contains(item))
        {
            var comparer = (CachingEqualityComparer<T>)Comparer;

            item2 = comparer.Other(item);
            return true;
        }

        item2 = default(T);
        return false;
    }

    private class CachingEqualityComparer<T> : IEqualityComparer<T> where T : class
    {
        public WeakReference X { get; private set; }
        public WeakReference Y { get; private set; }

        private readonly IEqualityComparer<T> Comparer;

        public CachingEqualityComparer()
        {
            Comparer = EqualityComparer<T>.Default;
        }

        public CachingEqualityComparer(IEqualityComparer<T> comparer)
        {
            Comparer = comparer;
        }

        public bool Equals(T x, T y)
        {
            bool result = Comparer.Equals(x, y);

            if (result)
            {
                X = new WeakReference(x);
                Y = new WeakReference(y);
            }

            return result;
        }

        public int GetHashCode(T obj)
        {
            return Comparer.GetHashCode(obj);
        }

        public T Other(T one)
        {
            if (object.ReferenceEquals(one, null))
            {
                return null;
            }

            object x = X.Target;
            object y = Y.Target;

            if (x != null && y != null)
            {
                if (object.ReferenceEquals(one, x))
                {
                    return (T)y;
                }
                else if (object.ReferenceEquals(one, y))
                {
                    return (T)x;
                }
            }

            return one;
        }
    }
}

请注意使用,WeakReference以免对可能阻止垃圾收集的对象的无用引用。

使用示例:

var hs = new HashSetEx<string>();

string str = "Hello";

string st1 = str.Substring(2);
hs.Add(st1);

string st2 = str.Substring(2);

// st1 and st2 are distinct strings!
if (object.ReferenceEquals(st1, st2))
{
    throw new Exception();
}

string stFinal = hs.AddOrGet(st2);

if (!object.ReferenceEquals(stFinal, st1))
{
    throw new Exception();
}

string stFinal2;
bool result = hs.TryGet(st1, out stFinal2);

if (!object.ReferenceEquals(stFinal2, st1))
{
    throw new Exception();
}

if (!result)
{
    throw new Exception();
}
于 2015-05-01T11:09:17.590 回答
3

我确实有这个要求,并且确实在 SO 上提出过要求,但是没有像您问题的细节那样,没有有用的回答。内置的一个选项是(System.Xml).NameTable,它基本上是一个字符串原子化对象,这是您正在寻找的,我们有(我们实际上已经转移到实习生,因为我们确实为 App 保留了这些字符串-生活)。

if (name == null) return null;
if (name == "") return string.Empty; 
lock (m_nameTable)
{
      return m_nameTable.Add(name);
}

在私有 NameTable 上

http://referencesource.microsoft.com/#System.Xml/System/Xml/NameTable.cs,c71b9d3a7bc2d2af显示其实现为简单哈希表,即每个字符串仅存储一个引用。

缺点?是完全特定于字符串的。如果您对内存/速度进行交叉测试,我很想看看结果。我们已经在大量使用 System.Xml,如果你不这样做,当然可能看起来不那么自然。

于 2015-05-01T15:06:09.543 回答
0

编辑3:

而不是索引字符串,将它们放在非重复列表中将节省更多内存。

我们在 MyObjectOptimized 类中有 int 索引。访问是即时的。如果列表很短(如 1000 项),则设置值的速度不会很明显。

i assumed every string will have 5 character . 

this will reduce memory usage
  percentage   : 110 byte /16byte  = 9x gain 
  total        : 5gb/9 = 0.7 gb  +  sizeof(Country_li , Province_li etc ) 

  with int16 index (will further halve ram usage )  
  *note:* int16 capacity is -32768 to +32767 ,
          make sure your  list  is not bigger than 32 767

用法相同,但将使用 MyObjectOptimized 类

main()
{

    // you can use same code
    foreach (line in myfile) {
    fields = line.split(",");
    yield 
    return 
        new MyObjectOptimized {
            Country = fields[0],
            Province = fields[1],
            City = fields[2],
            Street = fields[3],
            //...other fields
        };
    }

} 

必修课

// single string size :  18 bytes (empty string size) + 2 bytes per char allocated  
//1 class instance ram cost : 4 * (18 + 2* charCount ) 
// ie charcounts are at least 5
//   cost: 4*(18+2*5)  = 110 byte 
class MyObject 
{
    string Country ;
    string Province ;
    string City ;
    string Street ;
}


public static class Exts
{
    public static int AddDistinct_and_GetIndex(this List<string> list ,string value)
    {
        if( !list.Contains(value)  ) {
            list.Add(value);
        }
        return list.IndexOf(value);
    }
}

// 1 class instance ram cost : 4*4 byte = 16 byte
class MyObjectOptimized
{
    //those int's could be int16 depends on your distinct item counts
    int Country_index ;
    int Province_index ;
    int City_index ;
    int Street_index ;

    // manuallly implemented properties  will not increase memory size
    // whereas field WILL increase 
    public string Country{ 
        get {return Country_li[Country_index]; }
        set {  Country_index = Country_li.AddDistinct_and_GetIndex(value); }
    }
    public string Province{ 
        get {return Province_li[Province_index]; }
        set {  Province_index = Province_li.AddDistinct_and_GetIndex(value); }
    }
    public string City{ 
        get {return City_li[City_index]; }
        set {  City_index = City_li.AddDistinct_and_GetIndex(value); }
    }
    public string Street{ 
        get {return Street_li[Street_index]; }
        set {  Street_index = Street_li.AddDistinct_and_GetIndex(value); }
    }


    //beware they are static.   
    static List<string> Country_li ;
    static List<string> Province_li ;
    static List<string> City_li ;
    static List<string> Street_li ;
}
于 2019-04-04T14:30:50.060 回答