r/coding • u/Dunyvaig • Nov 13 '16
Why does Linus Torvalds prefer the code on the right? (TED talk in comments)
4
u/DannoHung Nov 13 '16
The psudeocode is confusing. If you have entry already and it's next points to the next element in the list, then why can't you just take the address of the entry and assign the value of next to its value. Skippping the walk altogether.
7
u/Dunyvaig Nov 13 '16
I didn't get the impression it was psudeocode, it's normal C, from what I understand. It might even be production code for all I know.
2
u/jdog90000 Nov 13 '16
What happens if the head of the list is null?
1
u/Dunyvaig Nov 13 '16
What makes you think head can be null?
1
u/jdog90000 Nov 13 '16
I guess if the list constructor requires a head it won't. Otherwise you can make a new list and call this method.
2
u/Dunyvaig Nov 13 '16
Another case is: What happens if the entry isn't in the list? I suppose the implementation doesn't do any hand holding. For your case, it's kind of saying you shouldn't be asking to remove items when the list is empty. For my case it is saying you shouldn't be asking to remove an item which isn't in the list.
5
u/abrahamsen Nov 13 '16
The behavior of the function is undefined (best case: it will crash) if entry is not a member of the list. "head" being NULL is a special case of this.
You could put an "assert (*indirect != NULL)" inside the loop to handle this (presumable) contract violation in a deterministic matter.
7
u/DannoHung Nov 13 '16
No type signature on the function, the locals are not declared, and the head is implied to be either global or from a self context, but not explicitly said to be.
3
Nov 13 '16
You can't just "take the address of the entry and assign..." because there's two cases: the case where the entry is the head, and the case where the entry is along the list. In each case you (kinda) do something different.
You need to walk the list to get the previous entry, in order to update its next.
The code on the RHS appeals to an underlying consistency in both the prev/next cases: they are both changing a pointer -- and the particular form of the while loop arranges it so that this pointer is the prev. element or the head as appropriate.
2
u/DannoHung Nov 13 '16
I don't see how indirect has the address of the previous node. Instead it looks like the suggestion is to just overwrite the current node with the value of next, which has the same effect of deleting current.
But at that point, I don't see why you need to walk.
3
Nov 13 '16
GOAL: update the next pointer on the previous element OR move the head pointer itself
If the head is the entry then the while loop doesnt run. So the head pointer is replaced.
If the head isnt the entry, indirect becomes the NEXT PTR on the previous element, which gets changed to the entry's next.
1
u/Silhouette Nov 14 '16
I don't see how indirect has the address of the previous node.
It doesn't. It has the address of the previous node's next pointer. The value of
*indirectis therefore the address of the current node. That is what you actually need to check to see whether the current node's address is equal toentryand what you actually need to change if it is and so you want to remove the current node from the list.The neat symmetry that the right-hand example exploits is that on the very first step, when there is no previous node, the
headpointer serves exactly the same purpose.1
u/DannoHung Nov 14 '16
I mean, I see what the argument is, but I'm confused by the types.
In the while loop comparison, it's dereferencing indirect and checking that it isn't equal to entry. Ok, so that means that at the point the loop breaks, indirect is pointing to entry, right? No?
1
u/Silhouette Nov 14 '16
Ah, OK. What you're missing could be that
entryis itself a pointer (notice the use ofentry->next), and soindirectis actually a pointer to a pointer.
157
u/VertiGuo Nov 13 '16
Here's a Medium post that discusses this: https://medium.com/@bartobri/applying-the-linus-tarvolds-good-taste-coding-requirement-99749f37684a
"But it wasn’t the line count that mattered. It was that if-statement. It’s gone. No longer needed. The code has been refactored so that, regardless of the object’s position in the list, the same process is applied to remove it."
76
u/Neebat Nov 13 '16
Fewer conditionals = better pipelining.
68
Nov 13 '16
The magic that is branch predictors negate most of the benefits that the processor would have (although there would be some small amount by simply not polluting the predictor table).
Linus primarily liked the code on the right because fewer branches mean the code is easier for the developer to reason about. There are minimal paths that this code can take to execute, less state in the head of the developer to maintain.
27
u/Gravitationsfeld Nov 13 '16 edited Nov 26 '16
Statements like this make me uneasy. Branch mispredictions absolutely can become a performance issue even with advanced predictors like in Intel CPUs.
99
u/AlphaGoGoDancer Nov 13 '16
It can, but IMO performance is not a good reason to prefer a coding style. Make it easy to understand and reason about, then profile it, then optimize if needed
53
Nov 13 '16
I'm hitting the upvote button as hard as I can.
Premature optimization is bad. Readable, understandable code is very, very good. Bugs are expensive in more ways than CPU cycles.
36
u/amm0x Nov 13 '16
The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.
-- Donald Knuth
18
u/erik Nov 14 '16
Whoa, I had no idea that Knuth is quoted for saying "premature optimization is the root of all evil" in two different ways. Here is the other quote that I was familiar with:
Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.
Which is interesting, because in this second quote Knuth is actually saying that he thinks it is worth worrying about efficiency in advance under certain rare circumstances.
8
u/ubernostrum Nov 14 '16
They're perfectly consistent, though. The general advice people give is first to write code that is correct, then profile it and, if necessary, make it fast. And Knuth does not contradict that; his advice is against trying to optimize "at the wrong times" and "in the wrong places"; the only correct time is once a working solution is implemented, and the only correct places are those demonstrated to be too slow in an already-working solution.
2
Nov 14 '16
So tl;dr first priority is to get the thing to work, the second priority is making it work fast.
2
u/Silhouette Nov 14 '16
the only correct time is once a working solution is implemented, and the only correct places are those demonstrated to be too slow in an already-working solution.
This last part is your own interpretation. Neither Knuth quote actually says that, and in some programming fields there would be experts who would strongly disagree with it.
2
u/ItsAConspiracy Nov 14 '16 edited Nov 14 '16
Belated pessimization is the leaf of no good.
-- Len Lattanzi
6
u/drunk_puppies Nov 14 '16
When you're building an application or a system, premature optimization is bad. For an extreme example, inlining CSS will speed up your page load, but will fuck you repeatedly for the rest of your project cycle if you start doing it on the first day.
When you are building fundamental components of libraries that are going to be run by millions of people billions of times, optimization is the only thing you should care about.
I think you completely missed the point of the advice against premature optimization if you think it applies to this bit of code.
*also what u/ubernostrum said
4
u/YouFeedTheFish Nov 13 '16
Depends on what you're doing. Game development requires a deep understanding of cache misses and prefetches. Can't optimize too early here..
1
u/RoadieRich Nov 13 '16
That isn't premature, though. That's based on profiling many previous applications, and knowing where the bottlenecks are.
3
u/YouFeedTheFish Nov 14 '16
No, I'm talking about optimizing very early in the design process. Check out this video by Mike Acton at Insomniac Games. It's about an hour and a half, but it changed my mind on premature optimization.
2
2
u/moratnz Nov 14 '16
Always optimise.
But generally optimise for readability, understandablility, and maintainability.
Optimise for performance at need.
-2
Nov 13 '16
I'm hitting the upvote button as hard as I can.
Premature optimization is bad. Readable, understandable code is very, very good. Bugs are expensive in more ways than CPU cycles.
1
u/jutct Nov 14 '16
Especially in code that's more complicated than this. The nice thing is that the code on the right is guaranteed to be faster even if only by a margin, because a predictor doesn't even have to weigh in on it.
-1
Nov 13 '16
Right, I'm acknowledging that the branch predictor may take a small hit here. But especially in the kernel, developers should be optimising for developer understanding and maintainability rather than a likely small performance benefit.
-2
u/frenris Nov 13 '16
branch mispredictions are an issue as are pointer dereferences. the code on the right can result in more pointer dereferences.
12
u/Madsy9 Nov 13 '16 edited Nov 13 '16
It's not just about better pipelining or better performance; code with less conditionals is generally easier to read and understand than code with more conditionals. And in this specific example, the pointer-pointer indirection also removes a bunch of special-cases, which is even better.
Conditionals and conditional branching is in my opinion the very definition of business logic. As an experiment in your free time, start a real project you can finish in a weekend or less, then abstract all your conditionals and loops away by separating and tucking them all into short functions. It might make your eyes twitch at first, but when you are done, your code should be incredibly readable. Like a list of sequential steps.
15
u/way2lazy2care Nov 13 '16
code with less conditionals is generally easier to read and understand than code with more conditionals.
That really depends. You can understand what's going on more easily maybe, but you might not understand the intention as well.
In the code above I don't find the non-conditional code easier to read even though it is probably better, though I'm not entirely convinced that it generally is outside of a kernel context.
6
u/dvogel Nov 13 '16
I totally agree. Even if you want to argue the underlying point about conditionals, this code excerpt seems a particularly poor motivating example. I suspect, mainly based on evidence from Code Complete, that the number of bugs related to confusion about pointer manipulation in C, especially indirect pointers, is an order of magnitude higher than the number of bugs where someone forgot to consider either an explicit or implicit path.
5
u/martinus Nov 13 '16 edited Nov 13 '16
This is not about performance optimisation, this is about reducing the number of possible branches to improve testability. When you don't have any if statements in your code, reviewing it and testing all possible pathes is so much easier.
8
u/dvogel Nov 13 '16 edited Nov 13 '16
The number of branches in the implementation has no bearing on the number if cases you need to test or consider during review. Your test cases should remain the same when the implementation changes. Both of these solutions are acceptable and should be subjected to the same tests.
3
u/martinus Nov 14 '16
How does a branch not increase the need for tests? That's the cyclomatic code complexity, to cover all that with tests you would need to test each independent path through your program. So as you get more branches, testing effort explodes.
5
u/dvogel Nov 14 '16
Consider the code snippet that is the subject if this thread. The branch in the left-hand code is for the case where the node being deleted is the first node in the list. Regardless of whether you use the left-hand code, the right-hand code, or another implementation, you should always have a test case for removing the first node in the list.
2
1
u/mtreece Nov 13 '16
While I absolutely agree with you, I have to point out that, if one isn't careful, you can find yourself in a situation where you've eliminated conditionals at the expense of excessive pointer indirection. Depending on your platform, those extra pointer indirections can be a burden on cache misses, which can cause their own performance woes.
1
u/Neebat Nov 13 '16
Linked structures as a rule are not very cache-friendly. Yes, the extra indirection might make it a bit worse, but not much. In Java, we have solid implementations of both array and linked lists, and so there have been studies on which is faster. Turns out, there is a very tiny subset of problems which are faster using a linked list. Reallocating the array for size changes doesn't cost much.
5
2
u/panderingPenguin Nov 13 '16
Couldn't you also just initialize prev to head instead of null? That also removes the special case.
3
u/erosPhoenix Nov 13 '16
No. If we did that, the final line would effectively be a no-op (head->next = head->next) and the element wouldn't be removed.
1
0
Nov 13 '16
[deleted]
30
u/Neebat Nov 13 '16
This is bad relationship advice.
17
2
u/sparr Nov 13 '16
Only if you date irrational people.
19
u/Neebat Nov 13 '16
"Our anniversary is a very special day."
"Yes, and I know a way to make it a day just like any other!"
54
u/bart2019 Nov 13 '16 edited Nov 13 '16
Basically it's most likely because the code on the right hand side avoids the extra conditional. One code to do it all. If you can avoid handling special cases because they're not special cases, then you avoid forgetting about updating them if you have to change the code at some time in the future.
This has been discussed recently under the subject of "code taste".
26
u/utricularian Nov 13 '16
I don't feel strongly about this at all, but feel strongly that people who feel strongly about this are feeling a bit too strongly.
yeah...
16
u/yiyus Nov 13 '16
I find the second way clearer. At least in my mind, it maps better with the concept of removing a link from a chain, which is the analogy I always visualize when working with linked lists. Moreover, it removes the special case for head and needs less variables, so it has less cognitive load and less possible points of failure.
11
u/kubatyszko Nov 13 '16
Removing that "if" statement alone is worth a ton, especially in modern CPU's where cost of branch miss is huge.
9
u/dorondoron Nov 13 '16
That doesn't really apply in this case though. You loop before the conditional is applied, breaking branch prediction to get out of the loop causing a flush. The instruction after flush may or may not flush some thing that's almost empty anyway.
8
u/Sean1708 Nov 13 '16
You can't assume that removing an if-statement from your C source will change the number of conditional jumps in your final executable. In fact gcc produces almost identical assembly for both functions, while clang does seem to produce code with fewer branches in the right hand function.
While a branch stall does have a large cost on modern CPUs, modern CPUs also have incredibly clever branch predictors which make branch stalls basically a thing of the past.
3
u/way2lazy2care Nov 13 '16
Another post about this came up on /r/programming a bit ago. There was a lot of good discussion in this comment chain
3
u/myhf Nov 14 '16
The specific metric that the right-hand version does better at is called cyclomatic complexity
5
2
u/Keltek228 Nov 14 '16
It still doesn't check for null head or the case where the element isn't in the list. I'd love to see that get "tasted" away.
3
u/kbob Nov 13 '16
Torvalds is starting to annoy me. I've been doing list mutation like that since he was in diapers, and now it's becoming known as "Linus' List Trick". Grrrr....
-2
2
u/GreenFox1505 Nov 13 '16
Won't this leak memory at the "entry" object? What am I missing here?
4
u/TheCoelacanth Nov 13 '16
Removing an entry from a list is not the same as getting rid of all references to it. You could be removing it from one list just to put it in another list afterwards.
2
u/dethb0y Nov 14 '16
This always reminds me of cargo-cult thinking: People find a successful, talented person and try to (as best they can) emulate them.
1
1
1
Nov 14 '16
The code on the right is standard Unix C idiom.
Just look at the while loop from P 229 of The Unix programming Environment written in 1984. Its the same sort of while loop idiom.
As a old timer, its the way we all wrote system code back then, and continue to do now.
1
u/WTFisareddit- Nov 26 '16
There's also a double pointer problem that Torvalds had presented, it's also worth a look at.
24
u/Dunyvaig Nov 13 '16 edited Nov 13 '16
In the following TED talk: http://www.ted.com/talks/linus_torvalds_the_mind_behind_linux
... Linus talks about how one implementation of
remove_list_entry(...)in a linked list is better than the other. I found myself bemused, seeing as I was thought that focusing on readability is better than being clever (unless you really, really need to optimize the thing you're working on). I am sure I'd waste 10x as much of a maintainer's time if I used the right implementation over the left implementation.Or it might be that I don't have experience with coding C, and the right implementation isn't that obscure as I thought. I'm more of a Python/C#/Java guy.