echolocation
echolocation

Reputation: 1120

Does the position of brackets and whitespace affect compiler times and/or run-time?

Often while looking at other people's code, I notice a variance in bracket placement for blocks.

For instance, some use:

int foo(){
    ...
}

Whereas others use:

int foo()
{
    ...
}

And a number of ways in between. Does this at all affect how fast the code is compiled? For instance, if I were to have a series of blocks such as:

int foo() { ... {... {... {... {...} } } } }

int bar()
{
    ...
    {
        ...
        {
            ...
            {
                ...
                {
                    ...
                }
            }
        }
     }
}

Where foo() and bar() are identical except for whitespace and bracket placement. Would the functions take different times to compile? Would one be faster at runtime than the other?

Would this be any different if this were to be expanded to several hundred or thousand nested blocks? Does this change based on the compiler used? Would it change for different languages, such as C#, PHP, Perl, etc?

Sorry if this seems like a lot of general or open-ended questions, just something that's always interested me.

Upvotes: 1

Views: 448

Answers (2)

Justin Ethier
Justin Ethier

Reputation: 134157

The first thing a compiler will do is perform lexical analysis to strip whitespace, comments, etc and transform the input into a series of tokens.

The full process is similar to the following, depending on the specific implementation:


enter image description here


Since the lexer passes a series of tokens to the parser any additional whitespace, bracket positions, etc could potentially slow down only the lexing phase. And even then the difference will not be noticeable unless you had an extreme case, like a GB of whitespace or something crazy like that.

Upvotes: 0

Puppy
Puppy

Reputation: 146910

Would the functions take different times to compile? Would one be faster at runtime than the other? Would this be any different if this were to be expanded to several hundred or thousand nested blocks? Does this change based on the compiler used? Would it change for different languages, such as C#, PHP, Perl, etc?

No. No. No. No. No. Virtually all sane compilers strip out whitespace almost immediately in the lexing phase. The other phases don't even know that there was whitespace.

The only way in which this could make any difference is the most hideously incompetently written compiler ever, and even then I'd be amazed (also a bug of this magnitude would make it so buggy it would be completely unusable).

Upvotes: 1

Related Questions