Whether variable name in any programming language takes memory space

后端 未结 10 1507
时光说笑
时光说笑 2021-01-05 17:44

e.g.

int a=3;//-----------------------(1)

and

int a_long_variable_name_used_instead_of_small_one=3;//-------------(2)
         


        
10条回答
  •  走了就别回头了
    2021-01-05 18:03

    For C++,

    $ cat name.cpp
    int main() {
        int a = 74678;
        int bcdefghijklmnopqrstuvwxyz = 5664;
    }
    $ g++ -S name.cpp
    $ cat name.s
            .file   "name.cpp"
            .text
            .align 2
    .globl main
            .type   main, @function
    main:
    .LFB2:
            pushl   %ebp
    .LCFI0:
            movl    %esp, %ebp
    .LCFI1:
            subl    $8, %esp
    .LCFI2:
            andl    $-16, %esp
            movl    $0, %eax
            addl    $15, %eax
            addl    $15, %eax
            shrl    $4, %eax
            sall    $4, %eax
            subl    %eax, %esp
            movl    $74678, -4(%ebp)
            movl    $5664, -8(%ebp)
            movl    $0, %eax
            leave
            ret
    .LFE2:
            .size   main, .-main
            .section        .note.GNU-stack,"",@progbits
            .ident  "GCC: (GNU) 3.4.6 20060404 (Red Hat 3.4.6-11.0.1)"
    $ 
    

    As you can see, neither a nor bcdefghijklmnopqrstuvwxyz reflect in the assembler output. So, the length of the variable name does not matter at runtime in terms of memory.


    But, variable names are huge contributors to the program design. Some programmers even rely on good naming conventions instead of comments to explain the design of their program.

    A relevant quote from Hacker News,

    Code should be written so as to completely describe the program's functionality to human readers, and only incidentally to be interpreted by computers. We have a hard time remembering short names for a long time, and we have a hard time looking at long names over and over again in a row. Additionally, short names carry a higher likelihood of collisions (since the search space is smaller), but are easier to "hold onto" for short periods of reading.

    Thus, our conventions for naming things should take into consideration the limitations of the human brain. The length of a variable's name should be proportional to the distance between its definition and its use, and inversely proportional to its frequency of use.

提交回复
热议问题