5.31: Time vs. Memory Tradeoffs
- Page ID
Of course, there are a few different ways to write the Slide Puzzle game so that it looks and acts the exact same way even though the code is different. There are many different ways the a program that does a task could be written. The most common differences are making tradeoffs between execution time and memory usage.
Usually, the faster a program can run, the better it is. This is especially true with programs that need to do a lot of calculations, whether they are scientific weather simulators or games with a large amount of detailed 3D graphics to draw. It’s also good to use the least amount of memory possible. The more variables and the larger the lists your program uses, the more memory it takes up. (You can find out how to measure your program’s memory usage and execution time at http://invpy.com/profiling.)
Right now, the programs in this book aren’t big and complicated enough where you have to worry about conserving memory or optimizing the execution time. But it can be something to consider as you become a more skilled programmer.
For example, consider the
getBlankPosition() function. This function takes time to run, since it goes through all the possible board coordinates to find where the blank space is. Instead, we could just have a
blankspacey variable which would have these XY coordinates so we would not have to look through the entire board each time we want to know where it was. (We would also need code that updates the
blankspacey variables whenever a move is done. This code could go in
makeMove().) Using these variables would take up more memory, but they would save you on execution time so your program would run faster.
Another example is that we keep a board data structure in the solved state in the
SOLVEDBOARD variable, so that we can compare the current board to
SOLVEDBOARD to see if the player has solved the puzzle. Each time we wanted to do this check, we could just call the
getStartingBoard() function and compare the returned value to the current board. Then we would not need the
SOLVEDBOARD variable. This would save us a little bit of memory, but then our program would take longer to run because it is re-creating the solved-state board data structure each time we do this check.
There is one thing you must remember though. Writing code that is readable is a very important skill. Code that is "readable" is code that is easy to understand, especially by programmers who did not write the code. If another programmer can look at your program’s source code and figure out what it does without much trouble, then that program is very readable. Readability is important because when you want to fix bugs or add new features to your program (and bugs and ideas for new features always come up), then having a readable program makes those tasks much easier.