3 ms·
It is a bit anal retentive, but there is sound reasoning behind declaring your variables in the narrowest scope possible. Google's C++ style guide ( http://goo
by sparky 17y ago
It is a bit anal retentive, but there is sound reasoning behind declaring your variables in the narrowest scope possible. Google's C++ style guide ( http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Local_Variables http://google-styleguide.googlecode.com/svn/trunk/cppguide.x... ) captures some of them. Another is cache locality of your stack, if you are in a language or project where that matters; by creating space on the stack as late in the game as possible, your stack access pattern tends more to the end of the stack than if you declare everything up top in no particular order. This is a really small micro-optimization though; the main point is that you want to know what type something is and what might have been passed to its constructor, on the screen at the same time as the code that uses it.
Another thought; if there is a mammoth difference between top-of-function and narrowest-scope-possible, that suggests that you may have very large functions, and might consider refactoring so that the difference between your method and his is small?
- PlanetFunk 17y agoThanks for the comment. Although I think there's good reason for declaring variables in the narrowest possible scope, I'm not sure it's enough of a reason to bring it up - especially if it's more about coding style, rather than best practice. The size of the functions isn't really an issue, but I see your point. If they're as small as the examples above, it doesn't make much difference.
- Daniel_Newby 17y agoFor primitive types, a modern compiler's dependency analyzer can get better stack locality than anything you can do. Therefore I like to put all primitives at the top so they are easy to find. Mutable composite types that use the heap should be scoped broadly, to reuse their heap buffer without touching the memory allocator. Example: C++ std::string. Immutable heap composites could be scoped narrowly to reuse heap as soon as possible. On the other hand that reduces locality of reference for the deallocator code, and probably spams the branch predictor. If the immutable is small and deeply nested, it should probably be broadly scoped because branch prediction is made of solid gold (unless the language is garbage collected, making deallocation branchless). Hmm... That got complicated. Stick them all at the top unless you are optimizing a nested loop.