I think I have came across a few times when I reformat some segment of code, it performed the way I wanted it to other than the other poorly formatted segment of code? Does code format affect performance? Or is that a myth?
8
In a compiled language, any superfluous whitespaces, comments or other elements without syntactical meaning do not survive the tokenization step of the compilation, so it doesn’t make a difference at all for the resulting binary (at least for the executable parts – some compilers might embed original sourcecode in the generated binary for debugging purposes, but those parts of the binary aren’t executed).
In purely interpreted languages, the interpreter needs to parse all whitespaces. So formating can actually slow down the interpreter a tiny bit. But more advanced* interpreters usually compile the code in-memory to an optimized representation (“bytecode”) before they execute it . In this step, whitespaces are usually also stripped, so it shouldn’t matter for runtime either.
*in this case “more advanced” means “anything you would use in a 2014 production environment”.
1
To the compiler/interpreter it matters very little how well formatted and/or commented your code is. It only increases the parsing time by a very tiny amount because the parser has more characters to process (and mostly skip).
In most languages, the compiler/interpreter would be perfectly happy if you present your code as a single long line without any comments at all.
On the other hand, for human readers (including you in a few months time) it makes a world of difference if the code is well-formatted, well-commented and easily readable.
With well-written code, you can usually glance over it to get an idea of what the code is doing. If the code has poor or no formatting,then you really have to pay attention to understand the code which takes significantly more time and energy.
The only time I think format matters is with dynamically downloaded code – ie things like javascript where huge blocks of comments and/or very long variable names will slow down the download, but even then this does not affect the compile time. (and the download time can be fixed by minimising the javascript file).
For compiled files, the source is just a collection of symbols separated by whitespace. The compile doesn’t care how these are formatted, a single long line would be just as good as a nicely formatted source file, as far as the compiler is concerned (admittedly some languages would care, eg Python that relies on formatting, particularly new line indentation, but even that doesn’t affect the speed of compilation).
Formatting is for people, not for computers. Its important for that reason.