views:

83

answers:

2

Hi,

I've implemented a simple calendar (message system) for my game which consists from:

 1) List<Event> calendar;

 2) public class Event
    {
    /// <summary>
    /// When to process the event
    /// </summary>
    public Int64 when;

    /// <summary>
    /// Which object should process the event
    /// </summary>
    public GameObject who;

    /// <summary>
    /// Type of event
    /// </summary>
    public EventType what;

    public int posX;
    public int posY;
    public int EventID;
    }
 3) calendar.Add(new Event(...))

The problem with this code is that even thought the number of messages is not excessise per second. It allocates still new memory and GC will once need to take care of that. The garbage collection may lead to a slight lag in my game and therefore I'd like to optimalize my code.

My considerations:

  • To change Event class in a structure - but the structure is not entirely small and it takes some time to copy it wherever I need it.

  • Reuse Event object somehow (add queue with used events and when new event is needed I'll just take from this queue).

Does anybody has other idea how to solve the problem?

Thanks for suggestions!

+1  A: 

You can allocate a group on events in start, and if you memory will end you can alloc next eg. 100 Event()'s.

And if you talking about queue, use Queue class. But if your doing queue operations on list, you delete elements in linerar time (in Queue class Dequeue get O(1)).

Svisstack
Good idea. I'll try. The calendar is not a queue. Events are added for a given time and I process them in ascended order. Maybe I should use some kind of sorted list - I'm using foreach on list now (with respect to the number of events in the calendar at given time the performance is good).
MartyIX
+1  A: 

I agree this may be premature optimization but if you would like to design with high performance in mind then checkout the Prototype Design Pattern

The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

  • avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

Together with the Object Pool Pattern

An object pool is a set of initialised objects that are kept ready to use, rather than allocated and destroyed on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object, it returns it to the pool, rather than destroying it. It is a specific type of factory object.

kervin