4

Apart from readability, are there any differences in performance or compile-time when a single-line loop / conditional statement is written with and without brakets?

For example, are there any differences between following:

if (a > 10) 
    a = 0;

and

if (a > 10)
{
    a = 0;
}

?

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
Jay
  • 1,210
  • 9
  • 28
  • 48
  • 4
    I'm amazed with this question... No, there is absolutely no difference. – SingerOfTheFall Nov 08 '12 at 11:13
  • http://stackoverflow.com/questions/4797286/are-curly-braces-necessary-in-one-line-statements-in-javascript – Pratik Nov 08 '12 at 11:13
  • Takes me back to the days of BASIC programming when there was a speed advantage in using one letter variable names. – john Nov 08 '12 at 11:15
  • @Pratik: http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated – Jesse Good Nov 08 '12 at 11:23
  • @JesseGood Oops, I tagged it that way, as it seemed a very basic level programming question applicable for many languages level. – Pratik Nov 08 '12 at 11:26

6 Answers6

7

Of course there is no difference in performance. But there is a difference in the possibility of introducing errors:

if (a>10)
  a=0;

If somebody extends code and writes later,

if (a>10)
  a=0;
  printf ("a was reset\n");

This will always be printed because of the missing braces. Some people request that you always use braces to avoid this kind of errors.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
pbhd
  • 4,384
  • 1
  • 20
  • 26
  • [Apple actually had a bug](https://medium.com/@jonathanabrams/single-line-if-statements-2565c62ff492) introduced owing to the very same mistake ! – Akshay Anurag Nov 19 '18 at 08:16
  • *[Those braces aren’t at fault. A lazy programmer is.](https://blog.codecentric.de/en/2014/02/curly-braces/)* – Marc.2377 Apr 17 '19 at 18:07
4

Contrary to several answers, there is a finite but negligible performance difference at compile time. There is zero difference of any kind at runtime.

user207421
  • 305,947
  • 44
  • 307
  • 483
2

No, there is no difference, the compiler will strip out non-meaningful braces, line-breaks etc.

The compile time will be marginally different, but so marginally that you have already lost far more time reading this answer than you will get back in compile speed. As compute power increases, this cost goes down yet further, but the cost of reducing readability does not.

In short, do what is readable, it makes no useful difference in any other sense.

Phil H
  • 19,928
  • 7
  • 68
  • 105
  • 1
    And that process is cost-free? – user207421 Nov 08 '12 at 11:24
  • @EJP Yes. In practice, the internal representation will be a tree, and there will be no brace nodes. But braces will determine how it builds the tree, and it's quite possible that the compiler will insert the missing braces, temporarily, in order to build the tree correctly. (It's more likely, however, that the compiler simply has two different rules, so the braces have no impact what so ever.) – James Kanze Nov 08 '12 at 11:58
  • @JamesKanze So scanning the braces and reducing two extra productions is cost-free? Please. – user207421 Nov 08 '12 at 12:17
  • @EJP: You have wasted more time pointing that out than you will ever get back in compilation efficiency. But I will update the answer to be clearer. – Phil H Nov 08 '12 at 12:27
  • As I already stated that the difference is 'negligible', your remark is pretty pointless. – user207421 Nov 09 '12 at 00:25
2

A machine code does not contain such braces. After compilation, there is no more {}. Use the most readable form.

md5
  • 23,373
  • 3
  • 44
  • 93
1

Well, there is of course no difference between them as such at runtime. But you should certainly use the 2nd way for the sake of maintainence of your code.

Why I'm saying this is, suppose in future, you need to add some more lines to your if-else block to expand them. Then if you have the first way incorporated in your old code, then you would have to add the braces before adding some new code. Which you won't need to do in 2nd case.

So, it is far easier to add code to the 2nd way in future, than to the 1st one.

Also, if you are using the first way, you are intended to do typing errors, such as semi-colon after your if, like this: -

if (a > 0);
    System.out.println("Hello");

So, you can see that your Hello will always get printed. And these errors you can easily remove if you have curly braces attached to your if.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 1
    And I would be more interested in `comments` from the downvoter here. – Rohit Jain Nov 08 '12 at 11:20
  • The downvote is due to the fantasy that the braces can be compiled in zero time. – user207421 Nov 08 '12 at 11:25
  • @EJP.. Yeah, that part I edited. At compile time there is some difference. – Rohit Jain Nov 08 '12 at 11:27
  • @SingerOfTheFall.. Well, it will also compile in Java. But there is a very rare chance that you add both `;` and `{` after a statement right? – Rohit Jain Nov 08 '12 at 11:28
  • @EJP.. And I don't understand, why two answers with same content, are responded with different reaction. The same content was given 2 upvotes in the `@pbhd's` [answer](http://stackoverflow.com/a/13288058/1679863) – Rohit Jain Nov 08 '12 at 11:30
  • And if you never expand the if/else block you wasted two precious key-strokes. As EJP would say, that's *finite but negligible* difference in your productivity. – jrok Nov 08 '12 at 11:35
  • And *I* don't understand why you're directing that to me. There is no accounting for upvotes or downvotes in general, unless you can get a response from the person/people who did them. – user207421 Nov 08 '12 at 11:36
  • @jrok.. Well, that is also a valid point. But, it also prevents a programmer from doing a mistake. Who might mistakenly expand the if-else block without adding a curly brace. Again this is also very rarely expected, but can be considered. Personally, I prefer the 2nd way of doing it. – Rohit Jain Nov 08 '12 at 11:38
  • @EJP.. Yeah, I understand. It's perfectly fine. cheers :) – Rohit Jain Nov 08 '12 at 11:39
  • @EJP Can you show some actual timings in which the presence or absence of braces makes a difference in the compile time? That's one of the most ridiculous statements I've heard to date. (The total file size might make a difference, but the biggest difference is going to come from templates and include files.) – James Kanze Nov 08 '12 at 11:48
  • @JamesKanze Probably not, because what I actually said, that you are over-reacting against, was that it is 'finite but negligible': however redundant braces cannot possibly be compiled in zero time. There is nothing ridiculous about either statement. – user207421 Nov 08 '12 at 11:52
  • @EJP It's perfectly ridiculous for anyone who's ever written a compiler. In both cases, you reduce the same number of rules. (More or less characters may affect compile time, but it doesn't really matter what those characters are.) – James Kanze Nov 08 '12 at 12:01
  • @JamesKanze Certainly not. In one case you just reduce ; in the other case you reduce '{' '}', and , *and* . And you have to scan more characters. What is ridiculous here is maintaining that there is zero difference. – user207421 Nov 08 '12 at 12:14
  • @EJP When I was writing compilers, I tried to measure it. The number of characters did make a difference, but it didn't matter whether they were braces or comments or whatever. The braces different. – James Kanze Nov 08 '12 at 12:46
  • @JamesKanze My position is that it is 'finite but negligible', and that the notion that extra tokens and productions can be compiled in zero time is a fantasy. If you can produce a proof of this fantasy let's have it. Your final three words are meaningless. – user207421 Nov 10 '12 at 09:36
-1

It depends on the rest of the coding guidelines. I don't see any problem dropping the braces if the opening brace is always on a line by itself. If the opening brace is at the end of the if line, however, I find it too easy to overlook when adding to the contents. So I'd go for either:

if ( a > 10 ) {
    a = 0;
}

regardless of the number of lines, or:

if ( a > 10 )
{
    //  several statements...
}

with:

if ( a > 10 )
    a = 0;

when there is just one statement. The important thing, however, is that all of the code be consistent. If you're working on an existing code base which uses several different styles, I'd alway use braces in new code, since you can't count on the code style to ensure that if they were there, they'd be in a highly visible location.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • Your opinions about coding style are not an answer to a question about performance, which specifically *excludes* readability from its scope. – user207421 Nov 08 '12 at 11:45
  • @EJP They are, never the less, the only valid reasons for choosing one style or the other. And they are important. (There are absolutely no performance differences.) – James Kanze Nov 08 '12 at 11:55
  • I have been a compiler writer since 1976. Kindly retract. Your answer remains irrelevant. – user207421 Nov 08 '12 at 11:58
  • @EJP I've written a number of compilers, and I've never noticed a difference. In one case, you reduce one rule; in the other, a different rule. Depending on how you look up rules, it's possible (but highly unlikely) that finding one rule might cost more than finding the other, but the difference could go either way. – James Kanze Nov 08 '12 at 12:04
  • I've never *noticed* a difference either: that's why I *very carefully* said 'finite but negligible'. The only way you can disprove that is by proving that the braces are compiled in zero time. You know perfectly well that they aren't. If you encounter an opening brace you have to push a new state, parse the statement, and pop the state when you encounter the closing }. You also have to scan the { and }. If the braces aren't there you only have to parse the statement. All the rest doesn't happen. Ergo there is a finite difference. – user207421 Nov 08 '12 at 12:11
  • @EJP The only way you can prove that the braces add to the compile time is by measuring. When I was writing compilers, we paid a lot of attention to compile times, because machines were very slow, and times were predictable. I was never able to measure a difference because of more or less braces. Today, the biggest immediate impact on performance will be locality. Do braces affect locality? Which way? The only way to answer a question concerning behavior is by measuring it. – James Kanze Nov 08 '12 at 12:44
  • Nonsense. It's an analytic truth. No experiment required. More instructions are executed, ergo more time is taken. Whether the 'negligible' difference is even measurable is another question, into which I have not entered. You said yourself that compilation time depends on length, which is quite correct: a well written scanner and parser are both O(N) in the length of the input. Extra braces => longer input => longer compilation time. QED. Still awaiting your retraction of your offensive comment. – user207421 Nov 09 '12 at 05:41
  • @EJP I will retract the word "idiot", since you do seem to understand compiler internals. On the other hand, I stand by my statement that if you can't measure the difference, there isn't one. Especially on a modern processor, where execution times are far more influenced by other issues, like locality, than by the number of instructions executed. (But the measurements I did were on a very much older system, and in the end, about the only thing which changed anything was the number of bytes actually read, or the level of optimization.) – James Kanze Nov 09 '12 at 08:18
  • Thank you, acknowledged. As to the rest, you are arguing with a straw man. I started out by saying that the difference is negligible, and I have already agreed that it is unnoticeable. What I don't agree is that the difference is zero, and I have disproven it. – user207421 Nov 10 '12 at 09:46