dynamic_cast vs static_cast preformance?

Can anyone tell me what's faster?

example 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 for (auto it = objects.begin(); it != objects.end(); it++)
	{
		if ((*it)->objectType == GameObject::tower)
		{
			Tower* tower = static_cast<Tower*>(*it);

			tower->Update(objects);
		}
		else if ((*it)->objectType == GameObject::enemy)
		{
			Enemy* enemy = static_cast<Enemy*.(*it);

			enemy->Update();
		}

	}


example 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

for (auto it = objects.begin(); it != objects.end(); it++)
	{
		Tower* tower = dynamic_cast<Tower*>(*it);
		Enemy* enemy = dynamic_cast<Tower*>(*it);

		if (tower)
		{
			tower->Update(objects);
		}
		else if (enemy)
		{
			enemy->Update();
		}

	}


I think I can (hopefully) guess example one is faster, which brings me to the next question: is this the best way to cycle though update functions with all game objects that share a base class [GameObject}? seems ok to me, just want some input.
Last edited on
static_cast is faster than dynamic_cast since dynamic_cast has an extra type check.

So, whether example 1/2 is faster depends on the effectivity of the extra check

if ((*it)->objectType == GameObject::tower) vs dynamic_cast check
Additionally those snippets might do a different things if Tower class has child classes which sets own objectType.

Usually having to resort to casts means that you made a desing error somewhere. You should really reconsider it and maybe make Update() a part of common class interface.
You can either pass objects to it (which would mean passing objects to Enemy's Update function, but it can just ignore it) or don't and store reference to it inside Tower object (will only works if you need to pass same container on all iterations) so it will not need additional parameter in Update function
Topic archived. No new replies allowed.