🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Question about a comment in as_context.cpp

Started by
3 comments, last by WitchLord 19 years, 6 months ago
In as_context.cpp, asCContext::ExecuteNext(bool createRelocationTable) you wrote // Remember to keep the cases in order and without // gaps, because that will make the switch faster. // It will be faster since only one lookup will be // made to find the correct jump destination. If not // in order, the switch will make two lookups. Could you clarify why the switch would only need one lookup? How would the compiler optimize this? Doesn't it still need to compare against each case until it finds the appropriate one?
Advertisement
The compiler optimizes this to a jump table, google for it if you want more information on that.
Exactly.

The value in the switch expression is used as index into a list of destination addresses. If the switch cases are not in order the MSVC compiler doesn't fully optimize this, and for some reason that I can't remember right now it needs two jumps instead of one to find the correct case.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

It's still using a jump table. It's actually rather simple. The switch statement itself becomes a jmp. It jmps by the value of the variable, more or less. After the jmp, it discovers another jmp - right to the proper code. Thus, two jmps. If they aren't in order, this technigue still works. Sometimes, the compiler can put them in order.

This isn't really any different from the method with the lookup table. It's just two jmps instead of a memory access and a jmp. I don't know why they can't use a table for out-of-order cases too. Maybe I'm missing something obvious?
Yes, that is what I saw when studying the switch code. I don't know the reason either.

The only reason I can think of to not use a single jump table is if the switch cases are far between, leaving large 'holes' in the table. That would cost too much in terms of memory and perhaps cache-misses that it wouldn't be worth it.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement