Skip to main content
gamedev.net
🔒 Locked

Performance question

Started by AshleysBrain Sep 2, 2006 at 6:14 PM 2 replies 400+ views
Original Post
AshleysBrain
AshleysBrain
I was just wondering, in my app, there's a kind of a gateway function pseudocode:
bool SomeClass::DoSomething {

	if (a)
		return DoThingBecauseOfA();
	if (b)
		return DoThingBecauseOfB();
	
	return DoNormalThing();
}
This function is called a lot, and for each instance of SomeClass, a and b never change. The question is, is it worth using a function pointer to cache the decision? In most cases, a and b will evaluate false, so how does a function-pointer call compare to two ifs in terms of performance? The difference will probably be negligable, but I was curious anyway.
Construct (Free open-source game creator)
stevenmarky
stevenmarky
You say for each instance of your class a and b never change?
Are a and b determinable at compile-time? If so you could use templates and eliminate the need for an if statement at all.
I would expect a deference to take longer than a boolean test, if it is super-critical time it.
hplus0603
hplus0603
C++ or C#? In C++, it's legal to create templates based on constants, which the compiler can optimize. Probably doesn't produce a "pure" assembly, though.

In C#, how about overriding the function in each subclass that needs to do A or B? That's kind-of what overriding methods is for :-) The normal thing could be called by the base, and the overridden functions would call up to the base.
enum Bool { True, False, FileNotFound };
AbandonedAccount
AbandonedAccount
When evaluating performance, the only way to know for sure what will happen is test it. That said, if your branches are close to 100% predictable (which you imply) the branches cost you virtually nothing so you're essentially wasting time optimizing this.

The performance cost associated with a function pointer is minimal (needing to grab an easily prefetched pointer), although optimizing compilers can get confused by pointers and bail-out of other cool optimizations. The cost of a comparison is approximately zero if correctly predicted or a pipeline flush if incorrectly predicted.

So if your branch is incorrectly predicted much at all the if statements can hurt performance. If you call the function a lot it will probably be correctly predicted every time after the first, but if the branch falls out of the branch prediction buffer you may mispredict a lot.

I would guess you are wasting time trying to have this code be optimal, and recommend you learn how to profile the bottlenecks in your code to focus optimization efforts where you can do the most good.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.