user2998964
user2998964

Reputation: 99

Most efficient type of array to iterate through

I have a "character" and the character have an array (or list, or dictinary) of "effects" applied to them. Each "effect" is a struct that changes certain parameters. What is the most efficient type of array to use in this case, and what is the best way to iterate through them if that may have to be used quite often.

EDIT: it goes something like this

public class hero { int level; public int moveSpeed; Dictionary<effect> = effects;

int GetSpeed (){
    int m = movespeed;
    foreach (effect in effects) {
        if (type = "movement")
            m += effect.value;
    }
    return m;
    }
}

public struct effect {string type; int value;}

public static void Main (string args) {
    hero Baragorn = new hero();
    Baragorn.speed = 10;

    effect swamp = new effect();
    swamp.type = "movement";
    swamp.value = -3;

    Baragorn.effects.add(swamp)

    printf(Baragorn.GetSpeed().ToString());
}

Upvotes: 0

Views: 121

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

It doesn't make sense to use a Dictionary when you have to iterate anyway. Dictionary is fast when you know the key you want to access already. They have no advantage over a List<Effect> or Effect[].

List<Effect> will be better if you have to often add/remove effects. You can not add/remove from an array easily, but you can do so with a List.

Effect[] will be better if the list of effects is constant or doesn't change very often. Adding/removing from an array is expensive, as the entire array needs to be copied, but if you don't do that often, Effect[] will be the right data structure.

Performance measures show that using for to iterate a list/array is faster than using foreach.

Upvotes: 0

Pablo
Pablo

Reputation: 75

For the difference in performance iterating and array with a for or a foreach see: http://www.dotnetperls.com/for-foreach

Or check: Performance of Arrays vs. Lists

The answer compares arrays and lists with for and foreach.

Upvotes: 1

Related Questions