Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Main thing to avoid with C++ is virtual methods. Once you understand how they're implemented, you will understand why (hint: vtables).

Why? Are you concerned by the additional pointer dereference? In a tight loop (or other performance critical repetetive code), the vtables for all the derived types and the target piece of code would be sitting in cache already, and the code pointed to by the vtable entry would also be in cache. You have to fetch the object/class/struct instance that you're operating on regardless of whether or not it has a vtable, so that's an unavoidable cost. So I don't see how it's all that expensive. It's just a freaking pointer dereference. I do agree that it can matter in some instances, but I generally have a long list of things to improve before I would try to minimize pointer dereferences on vtables. If you really are having to optimize on such a low level, you'd probably do better to worry about cache hits/misses and data layout in-memory first.



A pointer dereference can make all the difference in an inner loop. As usual, the answer is to profile, then to optimize.

No other dogma really applies.


I don't think it's the pointer dereference so much as the fact that you can't inline virtual methods.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: