Optimization.` Deep in the ocean an octopus hides from predators. It disguises itself on the ocean floor. When attacked, it releases dark ink.`For an octopus,` survival depends on escape. It optimizes to avoid being eaten. A C# program too can be optimized for performance, to work better and faster.`Benchmark.` We must take measurements. Use Stopwatch and your mission will become easier. Keep track of the numbers in a text file (the octopus lacks this advantage). `Benchmark `benchmark`Benchmark: memory hierarchy `memory-hierarchy`Benchmark: ProfileOptimization `profileoptimization`Benchmark: use Stopwatch `stopwatch`Methods.` Now consider your methods. Once your figure out the important ones, begin to apply optimizations. Attack excess allocations first. The ocean is deep and dangerous. `Methods: fast return `return-optimization`Methods: reduce call depth `method-call-depth`Methods: reduce method size `method-size`Methods: reduce parameters `parameter-optimization`Methods: reduce recursion `recursion-optimization`Methods: reorder parameters `method-parameter`Methods: return multiple values fast `multiple-return-values`Methods: store field in variable `local-variable-field-optimization`Methods: use AggressiveInlining `aggressiveinlining`Methods: use async `async`Methods: use const values `const`Methods: use pasted inline code `inline-optimization`Methods: view IL `il-disassembler`List optimizations.` The List is a beautiful thing. But if you use it foolishly, your program ends up in bad shape. A predator (like a shark) may eat it before it finishes. `Lists: count fast `count-array`Lists: prefer for-loop `list-contains`Lists: remove fast `remove-element`Lists: use capacity `capacity`Lists: use Clear `list-clear`Dictionary optimizations.` A giant squid signals danger. In a similar way the Dictionary signals a program that is fast. Use a dictionary if lookups are needed. `Dictionary: change add order `dictionary-order`Dictionary: increase memory `dictionary-optimization`Dictionary: measure memory `dictionary-memory`Dictionary: reduce data `dictionary-size`Dictionary: shorten keys `dictionary-string-key`Dictionary: test before adding `dictionary-test`Dictionary: use IEqualityComparer `iequalitycomparer`Dictionary: use memoization `memoization`Dictionary: use StringComparer `dictionary-stringcomparer`Dictionary: use TryGetValue `trygetvalue`Memory optimizations.` Memory is a physical thing. It has shape and size (like an atom). In our performance quest we should conserve memory—use as little as possible. `Memory: locality of reference `locality-of-reference`Memory: measure class size `class-fields`Memory: temporal locality `temporal-locality`Memory: use arrays `array-memory`Memory: use bit masks `mask-optimization`Memory: use BitArray `bitarray`Array optimizations.` Arrays store elements in a fast way. As the octopus hides, it could store its location in a compact array. This would help it escape faster. `Array: assign elements fast `array-optimization`Array: count fast `count-array`Array: flatten 2D array `flatten-array`Array: use Buffer.BlockCopy `buffer`Array: use byte array `byte-array`Array: use jagged array `jagged-array`Array: use lookup table `char-lookup-table`Array: use sentinel element `sentinel`Array: use separate arrays `memory`String optimizations.` Strings are immutable. Often we must create new strings as a program runs. These excess allocations are slow. We remove them if possible. `Strings: avoid Replace `replace`Strings: avoid ToUpper, ToLower `string-isupper-islower`Strings: combine format strings `format`Strings: fast for-loop `string-for-loop`Strings: fast int parse `parse`Strings: lowercase characters fast `char-lowercase-optimization`Strings: memory size `string-memory`Strings: path optimization `path`Strings: split on chars `split`Strings: ToString int optimization `tostring-integer-optimization`Strings: use ASCII `ascii-string-representation`Strings: use lastIndexOf `lastindexof`Strings: use short strings `string-performance`Regex optimizations.` In the deepest part of the ocean, we find regular expressions. But even Regex can be optimized. Often we optimize a Regex by removing it. `Regex: optimize `regex-performance`Regex: prefer string loop `regex-versus-loop`Regex: use Compiled `regexoptions-compiled`StringBuilder optimizations.` The StringBuilder is like a List. It grows as needed. After each operation, no allocation happens—and this speeds up programs. `StringBuilder: append ranges `stringbuilder-append-substring`StringBuilder: consider strings `stringbuilder-performance`StringBuilder: data types `stringbuilder-data-types`StringBuilder: fast int append `integer-append-optimization`StringBuilder: reduce appends `stringbuilder-append-performance`StringBuilder: remove concats `stringbuilder-mistake`StringBuilder: store data efficiently `stringbuilder-memory`StringBuilder: use cache `stringbuilder-cache`StringBuilder: use capacity `stringbuilder-capacity`StringBuilder: use chars `stringbuilder-optimization`StringBuilder: use Equals `stringbuilder-equals`Class optimizations.` Prefer classes to structs. When we pass a class to a method, only a reference is copied. With classes we avoid moving things in memory. `Classes: avoid structs `struct-versus-class`Classes: cache DateTime `datetime-performance`Classes: cache typeof `typeof`Classes: use static fields `static-field`Classes: use structs `struct`Classes: use tree `tree`Classes: use Tuple `tuple-keyvaluepair`Branch optimizations.` For survival the octopus does not spend its time evaluating slow logic. It moves quickly. For C# we speed up our branches with switches or for-loops. `Statements: avoid LINQ `linq`Statements: avoid yield `yield`Statements: hoist try, catch `exception-optimization`Statements: jam loop `loop-jamming`Statements: reorder if `reorder-if`Statements: unwind loop `loop-unwinding`Statements: use complex expressions `arithmetic-expression-optimization`Statements: use decrement `decrement-optimization`Statements: use for `for-foreach`Statements: use switch `if-switch-performance`Some research.` You can find many optimization tips in Code Complete. I recommend this book for some tips. Some strategies may not be useful in C#. Many are still relevant. `Quote: `Use a high-quality design. Make the program right. Make it modular and easily modifiable so that it's easy to work on later. When it's complete and correct, check the performance. If the program lumbers, make it fast and small. Don't optimize until you know you need to (Code Complete).`A final note.` As an octopus, hiding on the ocean floor is something to optimize for. In C# programs, optimizations to reduce allocations and reduce logical tests are more effective.