source: trunk/sources/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 6205

Last change on this file since 6205 was 6205, checked in by cneumuel, 8 years ago

#1522

  • simplified check for EventHandler (by simply checking for delegate)
  • special handling types which use a hashtable internally (dictionaries, hashset, hashtable, ...) (as discussed with swagner)
  • added testcase which shows a stack overflow if ThreadLocal is included and compiler is on Debug (it does not happen in Release)
File size: 3.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Collections.Specialized;
26using System.Reflection;
27using System.Threading;
28
29namespace HeuristicLab.Common {
30  public static class ObjectExtensions {
31    public static IEnumerable<object> GetObjectGraphObjects(this object obj) {
32      var objects = new HashSet<object>();
33      obj.CollectObjectGraphObjects(objects);
34      return objects;
35    }
36    /// <summary>
37    /// Types not collected:
38    ///   * System.Delegate
39    ///   * System.Reflection.Pointer
40    ///   * Primitives (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single)
41    ///   * string, decimal
42    ///   * Arrays of types not collected
43    ///   
44    /// Dictionaries and HashSets are treated specially, because it is cheaper to iterate over their keys and values
45    /// compared to traverse their internal data structures.
46    /// </summary>
47    private static void CollectObjectGraphObjects(this object obj, HashSet<object> objects) {
48      if (obj == null || objects.Contains(obj)) return;
49      Type type = obj.GetType();
50      if (ExcludeType(type)) return;
51      if (type.HasElementType && ExcludeType(type.GetElementType())) return;
52
53      objects.Add(obj);
54
55      if (type.IsSubclassOfRawGeneric(typeof(ThreadLocal<>))) return; // avoid stack overflow when the field `ConcurrentStack<int> s_availableIndices` too grows large
56     
57      // performance critical to handle dictionaries, hashsets and hashtables in a special way
58      if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) || 
59          type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) || 
60          type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
61          obj is SortedList || 
62          obj is OrderedDictionary || 
63          obj is ListDictionary || 
64          obj is Hashtable) {       
65        var dictionary = obj as IDictionary;
66        foreach (object value in dictionary.Keys)
67          CollectObjectGraphObjects(value, objects);
68        foreach (object value in dictionary.Values)
69          CollectObjectGraphObjects(value, objects);
70        return;
71      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
72        var enumerable = obj as IEnumerable;
73        foreach (var value in enumerable)
74          CollectObjectGraphObjects(value, objects);
75        return;
76      }
77
78      foreach (FieldInfo f in type.GetAllFields()) {
79        f.GetValue(obj).CollectObjectGraphObjects(objects);
80      }
81    }
82
83    private static bool ExcludeType(Type type) {
84      return type.IsPrimitive ||
85             type == typeof(string) || 
86             type == typeof(decimal) ||
87             typeof(Delegate).IsAssignableFrom(type) || 
88             typeof(Pointer).IsAssignableFrom(type);
89    }
90  }
91}
Note: See TracBrowser for help on using the repository browser.