I’m working on a C++ class assignment and I’d like some input. I’m not looking for ‘help’ with my assignment as much as I use class assignments as an excuse to practice writing ‘good’ code, and I’m debating between two solutions to the current problem I’m working on.
I’m storing roughly 4000 values in an STL map. One of the features of this program is to print out every value in my map. I have a class called ‘driver’ that handles the internal logic of the application and holds a reference to the map. I have a separate class for user interface.
What I was going to do was pass a function pointer to my driver, which iterates through the map and calls back to the function in my UI class. Would this be a bad idea performance wise at roughly 4000 function calls? Should I bite the bullet and simply call cout while iterating? I hesitate to do this because I’m trying to keep my user interface completely isolated from my program logic and data. I know in the end it really doesn’t matter as it’s just a class assignment, but assuming hypothetically this is code I would want to maintain in the long run, what would the ‘best’ practice be here?
Short answer: don’t worry about it. 4k indirect calls is not a big deal. If you’re worried about performance, do the following:
Remember that ‘premature optimization is the root of all evil.’
Slightly longer version: You could define your call back as follows:
Then, the driver can just pass the appropriate
mapiterators (describing the range of things to print). The callback then performs the output for every element, so you’re avoiding the repeated indirect function calls.