Code bloat
In computer programming, code bloat is the production of executable code that is unnecessarily long, slow, or otherwise wasteful of resources. Code bloat can be caused by inadequacies in the programming language in which the code is written, the compiler used to compile it, or the programmer writing it. Thus, while code bloat generally refers to source code size, it can be used to refer instead to the generated code size or even the binary file size.
Examples
The following algorithm is written in JavaScript, and can generate an HTML// Complex
function TK2getImageHTML
The same algorithm above can be rewritten to be less redundant and more efficient as follows :
// Simplified
function TK2getImageHTML
Code density of different languages
The implementation of generic programming mechanisms significantly influences the resulting binary size. Languages like C++ utilize a "stenciling" or monomorphization approach for templates, where the compiler generates a separate copy of the code for each distinct data type used. While this eliminates runtime overhead and allows for specific optimizations, it frequently leads to code bloat when many different types are instantiated. Conversely, languages like Java typically use type erasure, sharing a single copy of the compiled code for all data types by treating them as generic objects. This approach minimizes code size but can introduce runtime performance overhead due to the need for dynamic dispatch or unboxing.The difference in code density between various computer languages is so great that often less memory is needed to hold both a program written in a "compact" language, plus an interpreter for that compact language, than to hold that program written directly in native code.
Reducing bloat
Some techniques for reducing code bloat include:- Code refactoring a commonly used code sequence into a subroutine, and calling that subroutine from several locations, rather than copy and pasting the code at each of those locations.
- Re-using subroutines that have already been written, rather than re-writing them again from scratch as a new routine.
- Combine program analysis to detect bloated code, with program transformation to remove bloated code.
- Disabling/removing certain program optimizations, as they may actually hurt performance.
- Using code minifiers/obfuscators that strip unneeded whitespace/indentation and other things unimportant to a program running.