0

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());
}
8
  • 3
    Don't talk about your code, show it ;-) Commented Aug 29, 2016 at 11:45
  • Well, afaik, for loops perform slightly better when looping through lists. If that's what you are looking for. Commented Aug 29, 2016 at 12:15
  • 1
    Premature optimization FTW! Commented Aug 29, 2016 at 12:18
  • 1
    @uteist for loops perform better than foreach, but no matter wether you use a Effect[] or List<Effect>. Commented Aug 29, 2016 at 12:20
  • 1
    @uteist I understood this, I just wanted to add this to make sure the OP understands this, too. Commented Aug 29, 2016 at 12:25

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That answers my question.
0

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.

1 Comment

Yea, i simplified it for an example, the idea is to key it through enumerator so i can remove effects without iteration.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.