Question

I'm doing a compiler, and I'm using the System.out.println(); to print assembly;

And the code get bigger, and more complicate to understand. I want to know whats is the difference of efficiency between this and if I should or no:

System.out.println("iload");

Or:

private void printAssemblyCode(String code) {
    System.out.println(code);
}    
printAssemblyCode("iload");

It's only to be more readable. It's worth it or not doing this?

Was it helpful?

Solution

The efficiency is not much different due to optimizations in modern Java compilers, but it does not gain much flexibility. The only thing it lets you do is turn off printing in one location rather than many.

You would be better served by delegating to a logging framework. Java has built-in logging, and there are other frameworks such as Log4j.

Using a logging framework you gain several abilities your current code does not:

  • You can log to arbitrary streams: standard out, standard error, a file, a socket, etc.

  • You have additional diagnostic levels. Rather than on or off you can have error, warning, info, et al and you can control which diagnostic levels are output.

  • Logging messages can include additional information such as the class and line number where the logging occurred (if you pass along a Throwable), and the date and time.

  • All of the configuration is done through, well, configuration, not code. Rather than commenting out a line of code and rebuilding, you can edit an XML or properties file and you are done.

Once you get in the hang of using a logging framework it is just as easy as using System.out.println() but there is far more capability if you need it.

Finally, a logging framework typically requires a tiny amount of initialization but adds little or no noticeable overhead to the running process when you invoke its functionality.

OTHER TIPS

Putting the code into a method has a different advantage: If you ever decide to not print to console, you would only need to change a single line of code.

Hardcoding the print-to-console like that throughout your project is not a good idea.

Once you have a working version and want to continue with it then you'd have to go through and change how you pass the assembly to the calling code for further processing. One of the things you can do is change the prints to a call to a pluggable interface that collects the opcodes (not as strings) and a implementation that prints them to console.

The overhead of calling one more method to output something will be too small to notice, since I/O is much, much slower than computation.

The question remains how much more readable it is to use your custom print method rather than println directly. I would think it is small, but it could be worthwhile anyway, since the added cost is very close to 0.

Licensed under: CC-BY-SA with attribution
scroll top