开发者

Speed optimize - which is better?

Let's say that we build a game and we have a player character. That character in the game will do many actions, like walking, jumping,attacking, searching target etc :

public class Player extends MovieClip
{
   public function Player(){}
   private function walk(){}
   private function attack(){}
   private function jumping(){}
   ...
   ..
   .
  private function update(){}
}

Now, for every state or action we want to execute a different code. Now, how to do this? I can think of 3 ways.

1.With events - as I understand, event system is costly to use, so I'll skip this one. 2. With simple checks in the update() - something like if(currentStateAction) {doSomethingHere} or with switch statement. But what if the actions are not mutually exclusive, e.g. it can jump and attack in the same time? Than we have to use if() for every action, e.g. to do checks for every frame. 3. I came up with this solution on my own and I need to know is this better than option number 2:

//declare Dictionary. Here we will add all the things that needs to be done
public var thingsToDo:Dictionary = new Dictionary(true);

//in the update function we check every element of the dictionary
private funciton update():void
{
  for each(item:Function in thingsToDo)
  {
    item.call();
  }
}

Now, every time we need to do something, we add a element, like thingsToDo[attack]=attack; Or if we don't want to do something anymore: delete thingsToDo[attack];

In this ... system ... you don't need to check every frame what the object should do, but instead, 开发者_C百科you only check when is needed. It's like a event driving system. Say for example, the object don't need to check for attack until new enemy is spawn. So. when spawing a new enemy, you will add thingsToDo[attack] = attack; and etc.

So the question: Is this faster than option number 3? Any idea how to do this checking differently? Thanks.


You should probably focus on making it work the way you want (flexible, easy to maintain and modify), instead of making it as fast as possible. This is very unlikely to ever be a real bottleneck.

Premature optimization is the root of all evil, and all that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜