Which is preferred, method 1 or method 2?
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (
For Java programming language, the common practice is to declare local variables only when needed in a method.
void foo(int i) {
if (i == 1)
return;
Map map1 = new HashMap();
if (i == 2)
return;
Map map2 = new HashMap();
}
For C++ programming language, I also suggest the same practice since declaring variables with a non-trivial constructor involves execution cost. Putting all these declarations at the method beginning causes unneeded cost if some of these variables will be used.
void foo(int i)
{
if (i == 1)
return;
std::map map1; // constructor is executed here
if (i == 2)
return;
std::map map2; // constructor is executed here
}
For C, the story is different. It depends on architecture and compiler. For x86 and GCC, putting all the declarations at function beginning and declaring variables only when needed have the same performance. The reason is that C variables don't have a constructor. And the effect on stack memory allocation by these two approaches is the same. Here is an example:
void foo(int i)
{
int m[50];
int n[50];
switch (i) {
case 0:
break;
case 1:
break;
default:
break;
}
}
void bar(int i)
{
int m[50];
switch (i) {
case 0:
break;
case 1:
break;
default:
break;
}
int n[50];
}
For both functions, the assembly code for stack manipulation is:
pushl %ebp
movl %esp, %ebp
subl $400, %esp
Putting all the declarations at function beginning is common in Linux kernel code.