Goto Leads to Faster Code
pdoubleya writes "There's an article over at the NY Times (registration required) about Kazushige Goto, the author of the Goto Basic Linear Algebra Subroutines (BLAS, see the wiki); his BLAS implementation is used by 4 of the current 11 fastest computers in the world. Goto is known for painstaking effort in hand-optimizing his routines; in one case, "when computer scientists at the University at Buffalo added Goto BLAS to their Pentium-based supercomputer, the calculating power of the system jumped from 1.5 trillion to 2 trillion mathematical operations per second out of a theoretical limit of 3 trillion." To quote Jack Dongarra, from the University of Tennessee, "I tell them that if they want the fastest they should still turn to Mr. Goto."" Ever get the feeling someone wrote an article merely for the pun?
They told me never to use GoTo statements in my Fortran class at Lehigh. Lying bastards!
"As God is my witness, I thought turkeys could fly." A. Carlson
This isn't news, everyone knows GOTO results in faster code than GOSUB
I'd always been told that use of Goto led to a case of the BLAS in my code!
Those who can, do. Those who can't, write technology blogs.
Ever get the feeling someone wrote an article merely for the pun?
Good thing the headline didn't contribute to that at all.
Not Buzzword 2.0 compliant. Please speak english.
Whatever.
Goto isn't considered bad programming because it slows things down. It's considered bad programming because it leads to spagetti code.
And people who "meticulously hand optomize" their code annoy the crap out of me. Run it, tweak it, run it again. Was the second run faster? Then tweak some more.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
when computer scientists at the University at Buffalo added Goto BLAS to their Pentium-based supercomputer, the calculating power of the system jumped from 1.5 trillion to 2 trillion mathematical operations per second
Which is certainly good, but to me says more about the previous implementation than it does about Goto's work.
Although he also writes fast code, Mr. Bluescreen was criticised for the poor stability of his code.
Goto is considered harmful!
It was CIS 150, C++ was the language of the day (pascal before, java after.) I was taking an exam that was all coding. I remember extensive use of GOTO from my commodore days, so I used one in a test (the objective was to code something with as few lines as possible)
;)
I had the shortest working code in the class but the arse hole teacher failed me for it. Said something like "we don't teach goto for a reason. Yeah, it's in the book, but don't ever use it!"
Jerk. I should post his phone number on slashdot
Do not meddle in the affairs of sysadmins, for they are subtle, and quick to anger.
...To see who actually reads the article.
;)
Judging from the replies...not many people
Edgar Dijkstra can drop dead.
Oh, wait...
Seriously, though, how does a guy end up with a name like this in computer programming? It sounds made-up! Then again, I've heard some very, very odd names...
The World Wide Web is dying. Soon, we shall have only the Internet.
I'm in a programming class right now (literally: my notes are open in another window) and GOTO hasn't even come up. It's an intro-level class, but... I see WHY it's used, and it for sure has its purpose, but if there's a more efficient way to program, duh people are going to go for it. And "registration required"? Ha: http://www.bugmenot.com/ (And yes, the NY Times is on there.)
I studied CS, and we did get GOTO statements (Well "jump" to be true). This of course was in IBM390 Assembler.
Goto Considered Helpful?
-Loyal
I aim to misbehave.
functions impose overhead.
The thing is, "Goto" isn't logical.
Think about it. There is no valid logical operator that says, "Okay, skip everything in between and go to the end." There is no valid logical constuct that allows you to ignore conditions, or to skip steps without simplifying. It's no wonder its so damn hard to maintain Goto code...Our brains don't work that way!
Sure it's quick. How could it not be? There isn't anything to it...you don't have to check anything or clear anything, you just jump ahead.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
http://kerneltrap.org/node/553
goto in linux kernel code is not considered harmful. Linus said so in 2003!
This guy is clearly considered harmful.
http://alternatives.rzero.com/
DEC had an ultra-optimized math library (calculations on arrays, Fourier transforms, etc.), improved over decades by generations of PhDs. There were different versions of the routines for the different generations of CPUs, for the different cache sizes of a same model, maybe even for various speeds of RAM. Needless to say, the simple fact of linking against that library instead of the standard one improved the speed of math intensive code by a good 10 to 20 percent (those numbers out of my fuzzy memory, but that far from insignificant).
Add to that compilers that were producing top-notch machine language for the target architecture (producing images that ran twice as fast as what gcc gave you at best), CPUs that were spanking the rest of the world as far as floating-point performance was concerned, and you can understand why the scientific community has kept using Alphas for so long.
Point taken, but in the early days goto still made a lot of sense, but a lot of conventional, old practices have gone the wayside with compilers that are smarter and better optimizing, and with better standardization in languages overall.
The *first* time I learned C, goto was perfectly acceptible (yay K&R original C material).
But really, my point is that a computer doesn't see things in the sense of functions; it sees things in the sense of labels (memory addresses), and in a sense, programming using functions is simply another way of getting around labeling a routine.
"Victory means exit strategy, and it's important for the President to explain to us what the exit strategy is." G.W.Bush
Read TFA and dig a bit, then you will see...
>>Actually, GOTO is my last name and does not mean "go to." (Nor is it pronounced "go to"; the correct pronunciation of my name is more like "goat-toe.")
Good God! How many of you slashbot jerks even bother to sniff the article before launching into a tirade about structured programming etc.
Dumb asses, the bunch of you!
And people who "meticulously hand optomize" their code annoy the crap out of me. Run it, tweak it, run it again. Was the second run faster? Then tweak some more.
When we are talking about math routines (I do simulation programming for engineering applications) its much better if you have a f'ing clue about what you are doing than just *tweaking* and seeing if it works better. And when runs take hours, it often isn't even an option.
-everphilski-
10 Print "oh Mr. K. GOTO" 20 I=I+1 30 If I 5 Print "Domo" Else 50 40 GOTO 20 50 Print "I'm Kilroy! Kilroy! Kilroy! Kilroy!"
Assembler Leads to Even Faster Code
From TFA:
It is in the same sense that Kazushige Goto's business card says simply "high performance computing."
i.e., Goto is the name of the developer, not the name of the coding practice he's using! -- Paul
OpenSource.MathCancer.org: open source comp bio
... and he must have done something awefully wrong, based on his reputation.
I believe you are referring to Kazushige's cousin, Mr. Gosub.
Ahh, the fleeting glimmer of hope, that one day correct programming practices would be discovered incorrect and life would once again become easy.
But really, is this his real name? did he change it? It could make for some great marketing. "Need Speed? GoTo Goto!"
I would be open to suggestions for names in up and coming business ventures I could start based soley on the punability of my surname. But for the love of god, no viagra jokes.
If used properly, GOTOs can still leave the code readable and maintainable. Besides.... We've all been using GOTO's under different names. In C++, what do you think the 'case' statement or the 'break' statement is? It's essentially a GOTO. Still readable. Still maintainable. Bad programmers will leave code unreadable and unmaintainable regardless of whether or not they use GOTOs. Good programmers can use GOTOs with no problems.
RTFS
For spaghetti. RAmen.
He is your goto-guy :)
If I use GoTo and make most everything global then am I not saving valuable stack space?
Separately, there are some great logical solutions to problems involving the use of GoTo-- we use it to manage the class instance variables (and their states) in a multi-threaded application loop where the number of threads is adjustable at runtime.
Cogito Ergo Sum
Obviously he's the GoTo Guy.
"It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
Using GOTO is fine and readable as long as you never jump backwards.
Some programming concepts are cleanest when expressed with functions, some with loops and some with gotos. If you have a finite state machine with 7 states and non-trivial logic for transitions, using 7 well-named labels and gotos is cleaner than any other alternative. K&R C book is pretty slim. I think it's not too much to ask anyone to read it and use all the available language constructs and libraries appropriately.
Hum... that is why exceptions were invented.
I remember constantly wondering where the fuck dengo was and what was so special about the place anyway while reading that book.
The thing is, "Goto" isn't logical.
Your argument against Goto is even less logical. Goto is a conditional jump, where the condition is always true. It's an if (true) { do; }.
Our brains have plenty of Goto's hardcoded into them; "repeat" is typically implemented through in a "goto" fashion, but you'll want to ignore that if you're a modern computer. The correct way is to instead unroll the loop and have no jump instruction at all (if you can get around it).
Sigh. Why don't they teach assembly anymore. It should be a pre-req to learning higher level languages.
"Victory means exit strategy, and it's important for the President to explain to us what the exit strategy is." G.W.Bush
In general, I find it easy to follow as long as gotos always go the same direction (down)- and that we only have one or two labels in a function- we're fine.
Although, also in general, people who use gotos going up, or have more than two labels in their functions, or that otherwise avoid goto like it's some sort of plague tend to have other problems.
If I use GoTo and make most everything global then am I not saving valuable stack space..?
Separately, there are some great logical solutions to problems involving the use of GoTo-- we use it to manage the class instance variables (and their states) in a multi-threaded application loop where the number of threads is adjustable at runtime.
Cogito Ergo Sum
You're right! Jesus.
*Pours more coffee*
Mods on crack. I tell ya. Can't believe that made it to 5.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
I just knew my code is better with goto's than while's, for's, and all those other hidiously difficult to use statements.
Now if I just could fine the mail address of my CS teacher he'll finaly have to correct my grades from before.
...all these years...
Dependency hell? =>
had I mod points, you would receive one.
We don't limit our thought process to the article. Sometimes we GoTo a place outside the box.
Cogito Ergo Sum
IMHO, a well-positioned goto is more clear than a structural variable. For example, jumping out of a loop inside a loop is quite nice with a goto. There is no such thing as a double break.
-- Imperial units must die --
goto is OK because it can do something in any language that offers it, that no other construct in that language allows.
You can jump from inside the middle of one nested set of loops and/or tests directly into the middle of another set.
(USE WITH CARE!)
Without goto, you have to set a flag and then test that flag multiple times to do the equivalent. What a waste of time!
10 ?"goto statements remind me of 7th grade and looking through the hole in the girls changing room"
20 goto 10
Hey kids! Your uncle Sammy here, with a fun rainy-day Slashdot activity for you!
First: take an article which revolves around a pun, just like this one, to deliver a message which has a different meaning than the headline would suggest.
Next: Pick a comment-karma threshold. Two or three ought to do it!
Last: Count how many of the people at that level have completely missed the point of the article: specifically, that the "Goto" in the writeup is not a GOTO statement, but rather the name of a programmer named Kazushige Goto; that this particular distinction is supposed to be considered a bit of ironic humor; and, that this is, in fact, the reason that Hemos posted it "from the we're-punny-this-morning dept."
Hours of fun for everyone!
Please moderate the parent of this post and all others who hurried to post comments on the "GO TO" statement (-1, Redundant). These suckers who don't even read the summary in the scramble to get the first post should be reduced to the status of posting at -1. Thanks.
Well jesus fucking christ, it's a good thing you posted a comment telling us all about this! You could have saved some typing, though, and just said "guess what everybody! I didn't read the article, or even pay attention to the summary!!11!1!"
-b
myselfmusic
But you can't just unroll all your loops either since your instruction cache usage will be very bad in that case.
:)
Deciding which loops to unroll is left as an exercise to the reader
0 END
Strange women lying in ponds distributing swords is no basis for a system of government.
1 GOTO END
BEAT YA! Yours wont even get executed mwahahhahahahahaha!
of somebody which should read the article before answering and OBVIOUSLY DID NOT DO IT.
Please Moderate me -5 "Idiot, RTFA".
C. Sagan : A demon haunted world:
http://www.amazon.com/gp/product/0345409469/
visit randi.org
Ever assembled a desk or something after it was shipped to your place? Those instructions always have numbered steps and statements like "if you don't need to attach your desk to the wall, go to step 5". Makes perfect sense and since the steps are sorted, I can easily find step 5 in the manual rather than looking for a named label or (*horror*) closing brace with correct indentation.
Most courses if they mention GOTO at all, tell you never to use it ever. Maybe by not telling you about it, they assume that you won't know about it, and therefore never use it. Nobody in university does learning on their own time. The reason they tell you not to use it, is because it can make spagetti code very easily. However I've found there are good uses for it, and it can make code a little cleaner in certain circumstances. It doesn't pop up very often, but it can be used as a proper method of coding. I am aware that anything can be done with gotos, but at some points, goto actually produces nicer results then the non-goto equivalent.
Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
Not to bash your point too much, but my brain works that way :) I remember in school we had to write an assembly program in gcc and I used jmp instructions to dance around a block of code so much (I was trying for the smallest program) that I got my A paper back with my favorite teacher comment ever... "too complex."
The semicolon operator "don't start doing this thing until this other thing is completely done" has no place in logic, either. Programming languages aren't based on formal logic, and our brains _do_ work that way. And so do CPUs.
We've secretly replaced Slashdot with new Folgers Crystals - let's see if it notices.
Goto is used because it is more efficient from the processor's perspective. Function calls have additional overhead. Function calls are easier to follow than a chain of goto's, so most people consider the cost paid in processing time to be well worth the decreased time needed in implementation, testing, debugging, and maintenance.
I am still waiting for someone to provide a link that does not require registration. Until then the trolls have a free playing field.
Neither is there a logical operator for "while", "for", or any other flow control construct.
A lot of people complain about people never reading the actual articles before they comment, but it seems worse than that. People don't even bother reading the blurbs.
I wonder where the slashdot effect comes from then?
-sigh-
The *first* time I learned C, goto was perfectly acceptible (yay K&R original C material).
What the hell are you on about, I dont have a copy of k&r handy but i distinctly remember them saying something like "goto is inifinitely abusable and should be avoided".
Anybody who criticizes Goto Kazushige's Free Software credentials - he created a Linux/Alpha distribution called Stataboware, which among other things included an early version of his hand-tuned math library back in 1999 (it's now defunct, unfortunately).
10 Goto FirstPost
^C^C^C^C^C^C^C^C
Mod parent up!
Well, I was going to post an example of when goto can be used to improve code flow by streamlining multiple "early return" conditions, but sadly the LameAss(sic) filter rejected it. So you'll have to take my word for it.
*rimshot!*
From the article:
"Robert A. van de Geijin, a computer scientist who works with Mr. Goto at the Texas Center,..."
All right, a Japanese programmer named Goto, working with a non-Japanese guy name Geijin. That's too much.
Unfortunately, some languages, particularly older ones still in use today, do not.
Eh. If that was true, then you could use "if(true)" everywhere you use goto, and there would be no difference.
I disagree with the brain statement as well. There are very few neural functions that have no boundary conditions.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
That's not really a goto...it's just a conditional. If--->then--->else
A goto is like a derailed thought process. It would be like having a disjoint right in the middle of a sentence telling you to go farther along and do some unrelated thing for a minute, then jerking you back to what you were doing in the first place with another goto statement.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
This is all well and good, but... is the guy's name actually "Goto"? And if so... does he actually use goto statements, or is that just implied to make the article title more of a hook?
After all, it was Donald Knuth himself who, in "Structured Programming with goto Statements" (Computing Surveys, sometime in 1974), wrote "At the [year] IFIPS Conference, I was introduced to Dr. Eiichi Goto, who cheerfully complained that he was always being eliminated."
(Apologies for errors, as my issues of CS are in storage and I'm doing this from memory.)
My favorite ever comment was, "If I ever saw this in the real world, I'd fire you" attached to an "A" test paper with a programming question on it I'd managed to reduce to one line of nearly incomprehensible recursion.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
is the guy's name actually "Goto"?
Yes
And if so... does he actually use goto statements
The article doesn't speak of goto statements whatsoever.
Yes, functions impose overhead. however:
- if your function is small enough and your compiler smart enough, it can inline the routine, removing overhead preserving readability
- nobody can say where the time-critical code is without profiling. Most of the (fortran) code I handle spends 80% of the time zeroing arrays. There's not so much to optimize in this procedure, and optimizing the remaining 20% by filling the code with gotos is only a waste of time
- if the algorithm is slow, optimize. If it's still slow, change algorithm.
- last but not least. If you optimize the code to save some hour of computational cost but you obtain code which needs an additional month to debug, you are doomed to have a very bad time.
-- "If A equals success, then the formula is A=X+Y+Z. X is work. Y is play. Z is keep your mouth shut." - Einstein
Marvelous insight, Turing! Next time try reading something other than the headline before you post.
Actually it is goto. if (no_need_to_attach_to_wall) goto step5;
No, but they still work within boundary contructs, which is the point of a logical operator. While loops don't randomly disregard the truth value of their repeat condition, nor do For loops. But goto statements do, which breaks the big rule of logical operators...the truth value of the premise must be preserved.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
If wife has headache, GOTO sleep
If boss is on vacation, GOTO strip bar for long lunch
If in-laws are coming over, GOTO work and pretend there is a critical problem that requires your presence all night
If technical conference is in Vegas, GOTO it
loads of examples.
If work is boring, GOTO slashdot to kill an hour or two
"I have as much authority as the pope, I just
don't have as many people who believe it" - George Carlin
goto similar statements BRA,BEQ,BLT,BGT,etc are standard biz. you survive. you just gotta be diligent with how you arrange your assembly and maintain a style. (and not use assembly when it's possible.)
but all my EE microprocessor type classes relied on such things...
m.
Ever get the feeling someone wrote an article merely for the pun?
a per
There's of course the famous Alpher-Bethe-Gamow paper: http://en.wikipedia.org/wiki/Alpher-Bethe-Gamow_p
Just a quick question, why not do like this?
...
...
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
if (sc[i][j] == ch) goto DONE;
}
}
FAIL:
DONE:
Hum... Both blocks are wrong (for me). I prefer:
//Do something useful here
bool bSentinel = false;
for (i = 0; i < 100 && !bSentinel; i++) {
for (j = 0; j < 100 && !bSentinel; j++) {
if (sc[i][j] == ch) {
bSentinel= true;
}
}
But the true question that the article doesn't answer is:
Does Mr. GOTO use GOTO statements to optimize it?
From: Linus Torvalds
Subject: Re: any chance of 2.6.0-test*?
Date: Sun, 12 Jan 2003 12:22:26 -0800 (PST)
On Sun, 12 Jan 2003, Rob Wilkens wrote:
>
> However, I have always been taught, and have always believed that
> "goto"s are inherently evil. They are the creators of spaghetti code
No, you've been brainwashed by CS people who thought that Niklaus Wirth actually knew what he was talking about. He didn't. He doesn't have a frigging clue.
=====
This shows that Linus uses his common sense instead of blindly believing urban myths like "goto is always evil" and "x86 CPUs sucks".
We have given birth to a new acronym: RPFH Read Past the F**king Headline.
AT&ROFLMAO
...to CPU manufacturers.
How are they supposed to sell faster chips when he can make code run faster on them?
"Ever get the feeling someone wrote an article merely for the pun?"
Here on slashdot, I get that feeling all the time...
SIG: TAKE OFF EVERY 'CAPTAIN'!!
I can bet you most universities don't even teach "goto" logic and if they said anything about it, it was: don't use GOTO statements.
I was told this, unconditionally. I was told why as well, and had the matter illustrated with a mere 12 line example of horrific readability. I still use them though, when the call of the dark side is just too strong for me to resist.
May the Maths Be with you!
So, if Goto is so unlogical, how would you implement
int i;
for ( i = 0; i < 10; ++i ) { }
without a goto statement ? I challenge you... :)
- Leon Mergen
http://www.solatis.com
don't be so anal retentive. everyone knows it's a pun, it doesn't mean discussing goto is offtopic
did you forget to take your meds?
Say, dumbass, did you ever see how the program counter works in a CPU? It's all about skipping to the next step, unconditionally. What are you, retarded?
http://news.com.com/Writing+the+fastest+code%2C+by +hand%2C+for+fun/2100-1022_3-5972844.html?tag=nefd .top
I'm glad there are still people out there who realize that there is a time and place where hand optimizing code is actually beneficial. Regardless of which language it's not difficult to write inefficient code if you aren't careful (or even if you are and just having one of those days) and compilers don't always do a perfect job either.
Erik http://yakko.cs.wmich.edu/~rattles
people are always trying to eliminate him.
Those who do study history are doomed to stand helplessly by while everyone else repeats it.
When you start anthropomorphising code, it's probably time to take a break from computers for a bit...
Robert vand de Geijn, a collegue of Mr. Goto's at the University of Texas (my alma mater) came to give a seminar talk to us grad students at the University of Washington Applied Mathematics Department last school year. He was talking about using a new language to program on supercomputers. He showed us slides of how his code stacked up with the state of the art MPI code. In his analysis he also showed off Goto's BLAS. One of the issues with a BLAS is that if the size of your matrices and vectors do not line up well the cache size you will spend a considerable amount of time fetching data from memory. This causes periodic dips in performance when compared to matrix size. GOTOblas significantly improves performance in the regard. This guy GOTO is insanely good at what he does. And quit trying to be funny with your pedantic goto jokes.
887321 = 337*2633
Then most processors work with derailed processes.
It might be nice in a high level language to do things like switch, if..then..else, but at the core of it, the processor is just doing a comparison followed by a "jump if equal", "jump if not equal", "jump if greater than", etc, and finally just a "jump".
In every case, jump = goto.
The if..then..else/switch statements are just high level abstractions that lead to the very thing you say is a derailed thought process - jumps/gotos.
Of course, I prefer nice structures, with functions and all, but don't forget what it really means deep inside the computer.
As for a sentence, it's more like you're reading how to react to a bomb in your office and you get to "if the timer reads less than one minute, then run like hell and get out of here". It's pretty much a one-way goto, and quite practical.
I counted at least a dozen, and that's when there were only 60 comments in the story. I found that funny.
And, for the record:
1. Whining about missing the joke.
2. Explaining a joke about missing the joke.
3. Making a joke about missing the joke.
I was guilty of 3, and am now also guilty of 2, but have not yet been guilty of 1. I think.
Label not found
A fully functional web server written in Perl?
You don't make the poor richer by making the rich poorer. - Winston Churchill
We use BLAS for most of our Linpack runs, as it is the fastest set of generic libraries for the purpose. And you can ignore the complexity of coding for a P4, when you consider how much fun it is to code for Itanium, and to do it correctly.
The Internet has no garbage collection
Atlas is open-source and is a pretty good alternative. It is only a few percent slower than libgoto in most cases.
Save the bandwidth. Don't use sigs!
Maintainability. Go to type statements can make code ugly and unmaintainable fast (not that not using them insures maintainable code, coding styles and best practices are needed).
The entire point about production code is that it will be used by some else and maintained by someone else. Maintaining code can be much more expensive than initial development. Anything that reduces maintenence costs usually takes precedence over performance, annoyance of the initial programmer(s) and cpu time.
High end customized scientific computing is an exception. Speed is of the utmost importance and grad student programmers work cheap.
putting the 'B' in LGBTQ+
Mr. Goto's library may indeed be the fastest available, but a more important question in numerical methods is whether his library produces correct results. Even simple mathematical calculations are fraught with peril when done with finite arithmetic on a computer. Until you've taken a numerical analysis course from an experienced numerical analyst, you cannot appreciate this point enough.
Programming languages aren't based on formal logic
Imperative languages aren't based on formal logic. Functional programming languages, logic programming languages, and other declarative languages are deeply rooted in formal logic. While some tasks are more difficult in these languages, being able to reason about a program is really beneficial in a lot of situations.
(S(SKK)(SKK))(S(SKK)(SKK))
Read TFA and dig a bit, then you will see...
>>Actually, GOTO is my last name and does not mean "go to." (Nor is it pronounced "go to"; the correct pronunciation of my name is more like "goat-toe.")
Good God! How many of you slashbot jerks even bother to sniff the article before launching into a tirade about structured programming etc.
Dumb asses, the bunch of you!
int i;
i = 0; i = 1;
i = 2; i = 3;
i = 4; i = 5;
i = 6; i = 7;
i = 8; i = 9;
...then you're in Goto Hell.
I had a boss that was allergic to gotos. It pissed me off, but oh well.
And as the parent said, yes, they lead to more readable and efficient code. They are used in low level code like the Linux kernel and OpenSSL extensively, and when I do system level programming I use them too.
I use them when "the shit hits the fan", and I need to clean up my memory or whatever, and return from the function with an error code.
That same boss suggested code like the first one in the above example, or the infamous do { stuff; } while (0); with break statements. Well, break does not work well with nested loops now does it?
I think that the allergy to gotos came from the BASIC days where the goto was a line number and not a label, and the gotos then were equivalent to a longjump(), meaning that the jump could go anywhere in the code. C gotos can only go to a label within a function (I guess. If this is wrong, I've never seen anybody use it otherwise, nor should they).
Aside, from basic C style exception handling, I don't see a need to use a goto anymore than to use a switch statement for one or two cases (which is almost the same as a goto).
Also, Perl has good uses for goto, but its a little different. You can label individual loops with, uh, a label, and you can say stuff like last outer_loop or whatever you want.
Trust me, I've seen tons of crappy code that never used a goto, and I've seen tons of good code that have used goto. It does have its uses, and I will use it until something better is added to the C language.
Actually, unless the compiler optimizes away your goto by removing it and tacking the code that it was supposed to jump to right where the goto was, the goto will result in slower code because your fancy superscalar processor will not be able to fetch across multiple instruction cache lines.
From the article, "Recently there has been a quiet controversy around the Goto BLAS because Mr. Goto has been slow to offer his work as open-source software, the free model of software distribution.
Some programmers have suggested that Mr. Goto has not joined the open-source movement because he wants to protect his secrets and strategies from competitors."
Why does it matter? For a talent as unique as his, and as competitive as it is (according to the article), why is it so wrong to keep it proprietary and actually, uck, profit from his work? Why should there be a contraversy? Here's a thought, the zealots should go immitate him like they do every other commercial venture if its so important to them.
Anyway, from the article, he says that its not so and there will be an open source release at some point in the future. In anycase, the open source world isn't entitled anything and its shame that they should stirr up tension just because their savory jaws are dripping.
Good grief.
Thanks, Leabre
I've found myself, somewhat to my horror, using the following idiom in C++ quite a lot:
...etc, several times...
function()
{
if (false)
{
error:
printf("barf!\n");
return failure;
}
Object1 o1();
if (o.failed())
goto error;
Object2 o2();
if (o.failed())
goto error;
return success;
}
The jump target goes at the beginning, rather than the end, because C++ won't let you jump over a constructor. Previously, I was using nested scopes, which led to messy, overly indented code. This way at least produces cleaner code, although that 'if (false)' is a little startling... maybe I should consider wrapping it in a macro for readability's sake.
Mr. Case dramatically changes the way Mr. Goto's code looks. Mr. Goto sues...
Your argument against Goto is even less logical. Goto is a conditional jump, ...
No; Goto is a Japanese programmer.
Actually, it's the name of several Japanese programmers. Puns on their names go way back, to the weeks after Dijkstra's famous paper.
Those who do study history are doomed to stand helplessly by while everyone else repeats it.
Most /.ers should already know this, but you can bypass the New York Times' (free) registration by grabbing a username and password from BugMeNot.
"[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz
Goto considers harmful YOU.
--- What
Obviously,
what
you should have done
is insert
lots of
line feeds
and tabs
into
that one line.
Then it would have been a shining example of highly-structured code, and obviously much more readable.
Those who do study history are doomed to stand helplessly by while everyone else repeats it.
It's just two syllables... the first, "go", is pronounced like the "go" in gordon, not like the English word "go". The second, "to", is not like the English word "to", it is pronounced like the "to" in "tornado". Try saying "gohr-tohr". *
* Note: Pronunciation instruction may only apply if you live in the city of Boston. People living in other localities may need to contact the appropriate authorities for further instruction.
If it's for-profit but free, you're not the customer -- you're the product (e.g., the Slashdot Beta's "audience").
void f( int i ) { if( i < 10 ) f( i + 1 ); }
f( 0 );
Indeed; I use this approach for handling errors in a lot of routines. However, to please the anti-goto crowd, I usually define two macros:
.h file, you magically create goto-less code.
#define Done goto done
#define Fail goto fail
You'd be surprised how many people accept the resulting code as properly structured, when they vociferously reject any code that contains the "goto" token. By moving the goto out to a
People can be really dumb sometimes.
And I hope they never learn anything about machine code. Their whole world would shatter into little unstructured chunks.
Those who do study history are doomed to stand helplessly by while everyone else repeats it.
1 NOP
Look, I usually try not to lose my cool on this, but 90% of the comments here indicate that people think the key to this performance increase is the use of gotos in code. No, you fucking idiots. "Goto", in this case, is Goto-san, a Japanese person (pronounced "Goh-toh" with long o's, not "goh-tu"). The use of gotos in human-written (and read) code is always bad and nowhere is that actually suggested. Do any of you nitwits even understand what a pun is?
Join Tor today!
If a task requires N operations then it takes time O(log N) to execute because of Moore's law. It hardly seems worthwhile to make heroic efforts to incrementally optimize your code, especially when there is a pretty clear cap on the maximum possible efficiency you can squeeze out relative to processor speeds.
10 Print"Slashdot sucks";
20 Goto 10
I've hit Karma 50 and gotten a Score:5, Troll... I win!
_main:
ret
Get the order of magnitude optimization first, then quibble about individual instructions (i.e. make a dirty hack) only if you really, really need to.
Exactly, but quibbling is almost a waste of time if you can go down further by changing the algorithm... I mean, it's a waste of time trying to optimize the code for a bubblesort when you can implement a quicksort.
-- "If A equals success, then the formula is A=X+Y+Z. X is work. Y is play. Z is keep your mouth shut." - Einstein
I disagree. I split out the loops into a separate function (or use exception handling if available.)
fn1()
{
if (fn2()==0)
{
good stuff
}
else
{
bad stuff
}
}
int fn2()
{
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
if (sc[i][j] == ch) return 0;
}
}
return -1;
}
Speaking of compiler optimizations, if simply replacing control structures with goto made the function 30% faster, then either the compiler truly sucks, or the previous implementation was something horrible.
I don't mean to pick on you in particular, since half of the comments in this article are equally retarded, but what the hell? I know Slashdot's "early posts get modded up more" system discourages Reading The Fine Article, but are there really this many people who can't spare enough time to read the front page blurb before commenting?
Goto BLAS is not a BLAS implementation which replaces control structures with goto statements - Goto BLAS is a BLAS implementation written by a man named Kazushige Goto! Just in case anyone didn't catch that, Hemos even points it out again with "Ever get the feeling someone wrote an article merely for the pun?"
There's still at least ten Slashdot users here who actually understand the subject of conversation. If you're not one of them, would you please just read their comments, try to catch up, and stay silent until you're sure you aren't the "noise" in "signal to noise ratio"?
In CS courses below 300, we were told that goto was evil and should NEVER be used. They didn't even teach its use. In 300+ courses, we were given examples of why goto is sometimes the best approach producing easier to understand code that was also faster. In fact, a lot of time was spent by professors that did real work deprogramming brainwashed students who were taught that global variables should never EVER be used, goto is Satan, dynamic memory is for terrorists and all kinds of god awful ideas.
That is one of the problems with academia. There are too many Java hugging professors teaching the C/C++ courses and trying to push their own agenda. A Java loving professor completely deprived his students of an entire semester of C++ file/data structure instruction because of his Java pimping agenda. When the term project of "File and Data Structures in C and C++" is a Java project, you know there's a problem...
Yes, the original paper has goto as two words.
They that can give up essential liberty to obtain a little temporary safety deserve neither safety nor liberty.
Ben
Unfortunately for your argument most of those operations tend to be GOSUBs since you return from them!
How many times have somebody posted "optimization isn't worth the effort" or "modern compilers make optimization obsolete" on slashdot? I am not sure where that lie got started, but that fallacy has spread far and wide among programmers and especially project managers. All of the best programmers I know with carefully optimize their code - by hand. Yes, actually using a debugger, and sometimes even paper and pencil! Frankly, it is the lazy programmers who are most likely to claim that optimization doesn't matter.
From Kazushige Goto's webpage http://www.tacc.utexas.edu/~kgoto/#overview
...) and not improving TLB and virtual memory performance?
"During the last decade, a number of projects have pursued the high-performance implementation of matrix multiplication. Typically, these projects organize the computation around an "inner-kernel", C = trans(A) B + C, that keeps one of the operands in the L1 cache, while streaming parts of the other operands through that cache. Variants include approached that extend this principle to multiple levels of cache or that apply the same principle to the L2 cache while essentially ignoring the L1 cache. The purpose of the game is to optimally amortize the cost of moving data between memory layers.
Our approach is fundamentally different. It starts by observing that for current generation architectures, much of the overhead comes from Translation Look-aside Buffer (TLB) table misses. While the importance of caches is also taken into consideration, it is the minimization of such TLB misses that drives the approach. The result is a novel approach that achieves highly competitive performance on broad spectrum of current high-performance architectures."
So why have chip designers, software developers and academics been focused on impoving cache preformance (e.g. L1, L2, L3,
are these guys serious? of course optimized code is uglier, nastier and usually faster than nicer looking ones.
I think optimized code is very beautiful.
If only it were exceedingly popular in western culture and less popular in Japan.
Yeah, that's what I said -- changing from bubblesort O(n^2) to quicksort O(n log n) would be an example of an order of magnitude optimization.
"[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz
The functional programming community has been literally screaming for years that functional programming languages that have the tail call optimization/continuations can be much faster than programming languages that do not have it. Now here comes a guy that says 'goto' is faster. Of course it is faster, but it should be used within the proper abstraction, i.e. continuations, and not like 'goto 100' as it was in Basic.
Basically much time is spent in C programs in unwinding the stack, whereas programs that use continuations execute a simple goto (i.e. a jump) to the continuation, reusing the available stack space. This can lead to better memory usage, especially in recursive algorithms, which means the swap file does not grow with thrown-away stack data.
It's slower and less readable (consider if "Do something useful" is quite long)
High-performance libraries are great, but if they are closed-source can only EVER be great in the most restrictive case possible, which is useless in non-standard or heterogeneous environments.
For this reason, ATLAS is interesting to me. It's not as fast as it could be (by a long way), it doesn't support the full set of BLAS/LAPACK functions (which is crappy), it also doesn't provide optimizations on many chips that Linux will run on (doubly crappy) and it's a one-man project where the one man is massively overworked on the non-existant time available to maintain the project. On the other hand, it's Open Source (so I can add code I consider missing), it's Open Source (so I can compile on any platform I like) and it's Open Source (so I know the code will get some support from someone, for as long as it is in use).
Where I need more speed, and DON'T have the time to make the necessary changes - well, I'm screwed, because there is bugger all in the way of good BLAS/LAPACK libraries for Broadcom's SB1 processor. Not even Broadcom support their own processors. Such is life.
It's a small world and it smells funny; I'd buy another if it wasn't for the money; Take back what I paid (SoM)
If fn2() takes several arguments, you've done extra stack operations. Your exception handling code is also far away from the code that generated the exception.
So it's slower and less readable...
OK, I know that the article is not about GOTO statements. However, I'd like to respond to everyone saying that GOTO statements are bad.
The reason GOTO statements are bad is not speed. The reason GOTO is harmful is because it leads to spaghetti code, which confuses programmers. In pin-hole optimizations, GOTO can actually speed things up in many situations. And it's probably impossible on most architectures for your machine language not to have GOTO (jump) statements. In fact, there are architectures that have an explicit GOTO statement in every instruction.
Software sucks. Open Source sucks less.
That's fine, but I'd put "error:" after the return success. That way people aren't jumping backwards.
:) )
Of course, with C++, you really should be using C++ exceptions (or you shouldn't be using C++...
If book is boring GOTO last chapter. Say I have no appreciation for the 'finer classics of literature', but that's how I managed to read 'Tale of Two Cities' If paragraph is still describing door two sentances in, GOTO next paragraph. =P
Trying to debug his stuff was hell!
Real programmers know better than to do that.
You've either duplicated finalization code (by putting it before each return), or performed it in the calling function which would mean additional stack operations).
Your solution is either less readable or (much) slower.
Real programmers know that goto has it's purpose and don't hide from good tools. If you can't use goto properly, that's fine- maybe in another 10-20 years of programming you'll feel comfortable enough with your skills to use it.
Switch statements in particular have exactly the same behaviour as a computed goto: the program flow jumps from the start of the block to some label in the middle, and continues from there. If you look at it that way, fall-through is an obvious consequence, and not just there to trap inexperienced (and some experienced) programmers.
Of course, it's all kept in a single self-contained block, although there's no reason you can't nest them (actually, I'm not certain about that in C. I know I've done it in some other languages). But it's effectively a goto, nonetheless.
Too bad someone beat you to the bunch in 1994, in the IOCCC contest. Plus, this program is self-reproducing, too. Runs about as fast as the OS will allow any program to run.
http://www.ioccc.org/1994/Makefile
http://www.ioccc.org/1994/smr.c
http://www.ioccc.org/1994/smr.hint
I was always told using GOTO's was a sign of weakness......
TFA is about a guy whose surname is 'Goto'.
Wait until you read in an interview about Mr. Kazushige Goto's favorite food.
Italian.
Pasta.
Specially Spaghetti.
[/me ducks and runs away....]
"Sufficiently advanced satire is indistinguishable from reality." - [Tips: 1DrYakQDKCQ6y52z6QbnkxHXAocMZJE61o ]
In fact, a lot of time was spent by professors that did real work deprogramming brainwashed students who were taught that global variables should never EVER be used, goto is Satan, dynamic memory is for terrorists and all kinds of god awful ideas.
I'm not so much against telling learner students not to use these things as I am against teaching learner students that these things even exist at all. All these techniques are advanced, and students should be comfortable wit hthe basics before they are even exposed to the tricky concepts. A lot of misuse of these language feature comes from people who don't really understand what they're for.
May the Maths Be with you!
SYNTAX ERROR: LINE 10
Artix
Your Linux, your init.
Amen!
I'm so tired of people who say to _never_ use gotos. I understand why professors are saying this. The average computer science student often will use it in the wrong way. On average a class of computer science students will produce better code if they are told to never use gotos. But that doesn't mean that it never is good, only that the average programmer is a moron.
Not using goto's are one of those mantras that was coined by someone who hadn't thought things through, that got popular and were taught to students without critical thinking by professors with no real life experience.
I rarely use gotos (unless I'm coding in a language that doesn't support exceptions in which case it is a central part to how I centralize the cleaning up my stuff before returning an error code from my function) but I would be really pissed if it wasn't available when I really need it.
The Internet is full. Go Away!!!
I've been hearing a lot about Mr. Goto's code versus Atlas and ACML. Has anyone done a side by side benchmark to see who is best for all-round BLAS use?
Seriously. Computed goto is very useful for low-level
optimizations in things like high-throughput ethernet
drivers and such. It basically eliminates conditional
checks in cases where the condition stays the same
for a particular set of data. So instead ofone would haveIf the second part is executed in a loop, the savings of
not making an IF comparison accumulate fairly quickly.
3.243F6A8885A308D313
You do realise that a function call most certainly doesn't translate into goto statements?
There have been Jump To Subroutine instructions for longer than my knowledge of instruction sets goes back - it pushes the address of the instruction that should be executed following the execution of the function on the stack and jumps function (the address of which you give as a parameter).
Likewise, there is a corresponding Return from Subroutine instruction which takes the address off the stack and jumps to it.
The idea that functions are some sort of modern whimsical high-level construct is definately false, as is any idea that goto has ever been a good idea when you can use a function instead.
int i = 11;
(;-)
Those who do study history are doomed to stand helplessly by while everyone else repeats it.
Real programmers don't perform linear searches of 100x100 arrays when performance matters.
Look at the asm output of your compiler sometime, and ponder how many algorithms
end up with unconditional jumps. I can easily see how it might be possible to optimize away a stack operation here and a compare there by suggesting a jump in the right place, why not?
Just because it's *possible* to get a performance improvement, doesn't make it a win in every situation, right?
I'm sure the kind of mess Dijkstra was dealing with when he wrote the paper, was truly maddening. I'd be willing to bet that the kind of GOTO abuse by the ALGOL(?) and PL/I(?) programmers of the day were in *every* loop structure, and *very* common special case handling.
Bundle that with the kind of optimizations you had to do in the days of 8K core being a big machine, and the end result could be *really* ugly.
On the other hand, Dijkstra himself would probably use GOTO in the situation described in the article (e.g., porting LAPACK?)
-fb Everything not expressly forbidden is now mandatory.
for more technical info, see his site at the Texas Advanced Computing Center. pretty pictures and software tool downloads even.
I can attest to the efficiency of these routines. When I benchmarked a 22 processor Opteron cluster w/ Myrinet, the use of Goto BLAS resulted in a near 20% drop in CPU utilization but yielded a ~2 GFlop gain in performance using HPL (performance was roughly 60 GFlops total. Given more time, I could have probably coaxed more out of Linpack). This compared to ATLAS, the self-tuning BLAS and LAPACK routines that I painstakingly recompiled at least a few dozen times. Generally, ATLAS yields very decent results even compared to some of the "drop-in" Lin-Alg. routines found with most high-end compilers like PGI (ACML, PGI-optimized BLAS/LAPACK/SCALAPACK) but so far, nothing I have tried rivals the performance, in the case of HPL, of Goto's implementation. Great work, man!
Altought the ACM said so, it does not mean its true. It might just be desinformation.
How about you doing some tests and reach results-based conclusion?!
Even if you don't read the article at least read the summary. It's about a guy with the last name 'Goto'.
Required reading for internet skeptics
Not perfect, but at least the following isn't too unreasonable:
int err = 0;
foo = malloc(1);
if (!foo) err = -1;
if (!err) bar = malloc(1);
if (!bar) err = -1;
if (!err) baz = malloc(1);
if(!baz) err = -1;
if (err) {
if (foo) free(foo);
if (bar) free(bar);
if (baz) free(baz);
}
return err;
I like everyone else was trained *never* to use the dreaded goto statement. I'll grant that Pascal was more readable than Basic (with unlabeled gotos).
But, sometimes, it is actually better to use a goto to make the code more readable. The Linux Kernel, for example, uses gotos. I was pretty sceptical at first because it had been drilled into my head how unreadable code was with gotos in it. But, reading the code, I have to admitt is is much more readable for exception handeling, for example.
If the goto would not make your code more readable then don't use it. But, in the cases where it would avoid a bunch of sillyness trying to get out of a bunch of nested loops in case some error happened, then it makes a lot of sense.
Linus Torvalds (and others) explain the reasoning for this at:
http://kerneltrap.org/node/553
In short, there are both readability and efficiency reasons to use gotos.
Randy.Flood@RHCE2B.COM
goto statements remind me of 7th grade and looking through the hole in the girls changing room
Could you see into the boys changing rooms from in there?
Way too much! I used to get excited about a 10% speedup. But these days I just can't get excited about it when I know that next year's PC+old code will blow away current PC+optimized code. (Probably because, as everyone knows, time passes faster when you're older.) I'd rather spend time on algorithmic stuff that might make, say, an O(log N) improvement in speed that will continue to pay off more and more over time. But I suppose it's good to know there are young whippersnappers out there prepared to optimize the libraries I may have to use.
i=10;
Gravity Sucks
http://developers.slashdot.org/comments.pl?sid=169 534&threshold=1&commentsort=0&tid=156&mode=thread& pid=14129595#14131415
Gravity Sucks
Justin Case? That guy in Neuromancer?
And why's Mr. Goto suing -- did he take exception?
...when you're writing a game...tweak the difficulty of "Easy" to something [your mother] can cope with. -- onion2k
They (ie my uni) do teach assembly any more but why not really start with the fundamentals? Only with a solid grounding in semiconductor physics will they fully understand the implications of:
print "hello world"
but seriously
I'll agree with you that it's useful to know assembly but it was confusing, particularly for those who were reasonably new to programming.
We were introduced to assembler just before we got to pointers and I think that timing makes more sense than starting from scratch with assembly.
Assembler requires alot of hardware knowledge that isn't necessary for any higher level language and i think that when you start out programming you have enough on your plate without having to worry about memory and registers and interupts.
What's wrong with starting with the nice easy stuff? It's like in maths where they start with counting rather than, say, integration. Just because the first programmers started out with cogs and wheels (or slaves and a drum or whatever they did start with) doesn't mean it's the best way for everyone else to learn.
if "Do something useful" is quite long, I will write it in a separate function ;)
back when we decided they were a bad idea it was because "they're so damned slow"... usually, they take a WHOLE INSTRUCTION when compiled. But if you remove them, why that's zero instructions... huh, should be faster.
Next up... Fortran still faster than C.
-pyrrho
...when someone tells you to go to Hell, you are more indignant about the method than the destination.
-- n
I really can't believe none of you have undestood the article... It's not that kind of "Goto". It's not about an instruction, it's about a guy!!!!!!!!
The worst abuse of goto's I've seen was in a numerical analysis class.
Back in the 70's, one student turned in an assignment with a goto on nearly every other line!
It looked like she dropped or shuffled her deck of cards and used goto's to put them back in order.
The resulting program didn't work correctly and it took a good half hour or more to find the actual error. If I remember right, the failure was because she used a variable starting with 'I' for what should have been a FLOAT. Normally, I could pick those errors up very quickly.
Isn't that another Goto? (of hash-consing fame, which makes deep-equality on functional lists O(1) and often significantly reduces memory consumption by discovering duplicates at runtime)
;)
Well, I guess I could name my first-born Foobar Gosub and s/he should be a good computer scientist
Try Corewar @ www.koth.org - rec.games.corewar
Gai, that is SO gei
Thank you, Slashdot ! ;-)
Don't forget his nephew, Mr GOatse.
FWIW, Mr. Goto is pronounced goe toe. Not "goto" as in the BASIC construct.
If you can't use goto properly, that's fine- maybe in another 10-20 years of programming you'll feel comfortable enough with your skills to use it.
It's the opposite, 10-20 years ago I was quite comfortable using gotos - before I learned the basic principles of good C programming, mainly how to avoid spaguetti programming and break down your code into smaller meaningful routines.
Regarding stack overhead, have you heard of inline functions? You can still write good readable code and let the compiler do all the dirty work, thank you very much. You may not feel comfortable enough to take advantage of the compiler with your current skills, but maybe in another 10-20 years...
You didn't read what I said, did you? I can't put it at the end because you can't jump over a variable declaration in C++. (Because you can't jump into a greater scope than the one you're currently in, but you can jump into a lesser one.)
And I can't use exceptions because this is an embedded device where I can't afford the 2kB-per-stack-frame hit that enabling exceptions in gcc gives me.
This always reminds of how "Label not found" was translated as "Volumenaam niet gevonden" in the Dutch version of MS-DOS.
.BAT file uses GOTO and specifies a nonexistent label, the translation to "volume name" is completely incorrect. .BAT file, it took me quite some time before I understood what was happening.
The translator apparently had seen the DIR output "Volume in drive A: has no label" and believed that the "label" is referring to a "volume label" and translated it as "volumenaam" ("volume name").
But when a
When I first got this errormessage running a
How many of you botherd to read the article? This sounds like a very deep hoax.
e nt=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&q= %22van+de+Geijin%22+%7C+%22Mr+Goto%22+%7C+%22Dr+Go to%22&btnG=Search
An Asian Dr. Goto?
A non-Asian Dr. van de Geijin?
The BLAS?
A quick google of "van de Geijin" | "Mr Goto" | "Dr Goto" brings up 12,100 hits.
http://www.google.com/search?hs=SIB&hl=en&lr=&cli
Dunno.
THINK! It's patriotic
[Disclaimer: 3rd party here. I'm replying to your post, but the grandparent needs to be slapped as well.]
>Yeah, that's what I said -- changing from bubblesort O(n^2) to quicksort O(n log n) would be an example of an order of magnitude optimization.
I can't help myself. You set yourself up the bomb. First of all, the term "order of magnitude" refers to power 10. Consider the runtimes of three algorithms: A = 0.11, B = 1.0, C = 9.9. A and B are within an order of magnitude of one another, and B and C are also within an order of magnitude of one another. However, A and C are approximately 2 orders of magnitude apart.
Second, going from O (n^2) to O (n log n) is not an "order of magnitude" difference. It's difference in the order/degree of the polynomial. They're similar terms, but they have quite different meaning. For inputs less than n=59, n^2 and n log n are within an order of magnitude, and it is also possible to pick two different n log n algorithms that are always more than an order of magnitude apart.
Third, never argue that quicksort is O (n log n), because it's not. It's only n log n on the "average" case, but it's still n^2 in the worst case. There are adaptive modifications to quicksort that make it n log n in the worst case by recursively selecting the best pivot; however, such adaptive quicksort algorithms are usually nowhere near as fast as heapsort and its variants. When you call qsort in C, you just get the plain vanilla version of quicksort that has n^2 worse case runtime. Its n log n "average case" is about 30% faster than a good heapsort (* this depends on the things like the relative cost doing memory writes vs comparisons). To me, the "average" savings of 30% is usually not worth the chance that my program will unexpectedly freeze for a few seconds (or worse).
In short, I do not recommend blindly using qsort instead of bubble sort, which is potentially faster and is always more stable. If you're going to blindly pick another comparison sorting algorithm, choose heapsort. If you're only sorting integers, use a radix sort.
Well, you beat me to my punch line. Cheers!
Indeed. For the average Merkun, the easier and closer pronunciation would probably be the two words go toe , with the accent on "toe". (No offense to the GP poster, but what's up with the "r"s?) Strictly speaking, there are only five Japanese vowels, and they are all flat, very like what you get with Spanish. Vowel length is another important pronunciation distinction, but this doesn't happen in English, as this language uses syllabic stress instead. That's why you may sometimes see the Japanese surname Goto variously spelled as Gotoh or Gotou, or even with diacritics as Gotö or Gotô, to emphasize that the second "o" is supposed to be long.
Just my ¥2 as a Japanese-English translator. Eigo de no hatsuon ha dou de mo ii n da kedo, dekireba, chikai hodo ii ja nai desu ka.
"What in the name of Fats Waller is that?"
"A four-foot prune."
Regarding stack overhead, have you heard of inline functions? You can still write good readable code and let the compiler do all the dirty work, thank you very much. You may not feel comfortable enough to take advantage of the compiler with your current skills, but maybe in another 10-20 years...
You're kidding right?
Let me guess, you also run everything with -funroll-loops, don't you?
It's the opposite, 10-20 years ago I was quite comfortable using gotos - before I learned the basic principles of good C programming, mainly how to avoid spaguetti programming and break down your code into smaller meaningful routines.
I'm so glad the Linux kernel developers are 10-20 years behind you then.
Goto doesn't produce spaghetti code- you do. That's the problem. If you want to blame it on goto, fine, but inlining functions far away from their exception handlers is still spaghetti code.
By the way, most C compilers don't avoid the stack operations when inlining- most of the time they can't- they simply avoid the call routine.
I misread these: as (blaming slashcode) instead of what you probably meant.
And I can't use exceptions because this is an embedded device where I can't afford the 2kB-per-stack-frame hit that enabling exceptions in gcc gives me.
I covered that: or you shouldn't be using C++...
into thinking that gotos can't give faster code. I demonstrated this to a CS guy who looked at my goto with disgust. I replaced a for loop with an if (...) goto label; statement in my C code and out came improved performance. Gotos are useful in coaxing gcc based compilers into giving up loop optimization and leaving it to the guy who should worry about it in the first place - the user. The other compilers are so bad they don't matter or are so good I don't have to worry about.
Je me souviens.
But that would be an infinte loop!
:)
Or am I missing something?
Of course I'm talking about using goto. What else would I be talking about?
I'm trying to teach myself to set people on fire with my mind... Is it hot in here?
The main place where goto seems to foul up compilers is where it makes the control-flow graph (CFG) something more complicated than the graphs that arise from normal conditional flow. CFGs arising from normal nesting control-flow constructs can be drawn on a 2-D surface with no lines crossing each other. The same can't always be said of code littered with gotos.
--Joe
Program Intellivision!
Exceptions are very slow and should be used only for exceptional cases. The general suggestion is to never use exceptions for defining control logic in the code where performance matters.
Your comment goes more towards validating my comment than against it, so I don't understand why you said it. Instruction logic "goto" statements may be a jmp instruction, but the fact is, it is still a jump, which is functionally, goto. Hell, I'm sure if you compiled an app using a goto jump and decompiled it, you'd most certainly find it.
The same goes for a lot of functions (depending on the programming language). If the function isn't inlined during compilation, the compiler will simply load the addresses/data of what's needed for that instruction into a register, jmp to the location of the function, complete the function, and return back to where it was in order.
As for the "no use for a goto when you have a function"; there are a _lot_ of instances where a jump instruction is useful, where a function simply won't do what you want to do. For example, inside of a switch or nested if statements, etc. There are situations where jumping simply can't be avoided. The reason they teach against it is simply because people tend to use it badly; it leads to running off the stack, memory leaks and they are typically difficult to debug. However, I'd love to see you write a kernel without using a goto statement somewhere.
"Victory means exit strategy, and it's important for the President to explain to us what the exit strategy is." G.W.Bush
I like using goto for cascading error handling in functions performing allocation. This avoids redundant error-handling code and extraneous flag variables.
However, this is *structured* use of goto, in such a way that one essentially doesn't need to look at the destination (and if one does, it's on the same page, and ordered -- foobar_error10 is the first label, then foobar_error9, then foobar_error 8...).
I agree with the general concept of avoiding goto. The initial complaint about goto was that it makes code hard to read and maintain.
The easiest-to-read code structure that I've ever seen is a tree -- function foo calls function bar and function baz, each of which call their own functions. Procedural programming follows this structure.
Code that uses goto for general control flow is completely unstructured -- instead of trying to follow the control flow of a tree, it's trying to follow a randomly-connected graph.
Every function pointer (and setjmp()/longjmp()) in C breaks this beautiful, easy-to-read tree, so minimizing use of function pointers is quite useful.
I don't know why so many people get hung up on OO. Reading OO (with polymorphism) is like reading a bunch of little one-level bushy trees that aren't connected to any of the other trees.
Any program relying on (nontrivial) preemptive multithreading will be buggy.
One problem with "optimization" is that often the wrong thing is optimized.
For example, Someone might be able to implement a convolution (dot product) using the regular O(N^2) formula... For a vector of length N, this will result in O(N^2) floating-point adds and multipications being performed... Loop-unrolling could be used to keep all the units on the P4 busy...
However, the same result could be computed using a FFT, which is O( N Log2 N ) in # of adds & mults. Thus, this method requires significantly less computation [picture what happens when N=128], and a tad bit more memory. This implementation will not fully utilize a P4's arithemtic units although it would likely complete in far less time than the first method.
Thus, if someone is trying to show off how fast their new processor/supercomputer/cluster can be, they may not use the fastest implementation!
I recall seeing a few "supercomputer" specs recently that advertised "TFLOP/s" rates that were calculated based upon the maximum instruction bandwidth... This is deceptive advertising since even highly compute-intensive programs will not have an instructions stream composed solely of floating-point arithmetic... (And if a huge number of floating pointer operations are being done without any loads/stores, then perhaps there is a way to simplify the calculation!)
People usually refer to Amdahl's law for parallelizability... But a similar concept exists when taking about instruction mixes and functional units.
How do you deal with functions that perform a transaction -- i.e. operations that must be all rolled back if any operation fails?
For example:
int alloc_func(void) {
r = malloc(30)
if (!r) goto alloc_func_error1;
t = malloc(20);
if (!t) goto alloc_func_error2;
q = malloc(25);
if (!q) goto alloc_func_error3;
return 0;
alloc_func_error3:
free(t);
alloc_func_error2:
free(r);
alloc_func_error1:
return -1;
}
I mean, in C++ you can get this by having code that runs when variables go out of scope, but in C, this seems to me to be a pretty good way of dealing with the problem.
Any program relying on (nontrivial) preemptive multithreading will be buggy.
I can safely say that, regardless of what's easier to write, functional code is much harder to *read*.
Procedural code (C w/o function pointers and setjmp()) follows a simple, easy-to-read tree structure.
In functional code, I can't just look at some dead code and know what code is being executed ("Oh, so this variable that's being executed is a function returned from this other function that took a function that was returned from another function a while later...now *what* code, exactly, does that mean is being run?")
Any program relying on (nontrivial) preemptive multithreading will be buggy.
Goto statements are deterministic, just like the others.
I still maintain the point that designing a monolithic kernel in 1991 is a fundamental error. Be thankful you are not my student. You would not get a high grade for such a design...Writing a new OS only for the 386 in 1991 gets you your second 'F' for this term. But if you do real well on the final exam, you can still pass the course.
-- Andy Tanenbaum, flaming Linus Torvalds for perceived design flaws in Linux
Any program relying on (nontrivial) preemptive multithreading will be buggy.
I've always heard GOTO was faster, that was never the problem. People don't like them because of maintainability. OOB is easier for large complex applications and tracing a mess of GOTO statements, especially on code that isn't yours, is a nightmare!
-Jesse
First post! (just in case I am...)
"COME FROM" http://catb.org/~esr/jargon/html/C/COME-FROM.html
"A gun is a tool, Marian. No better, no worse than any other tool. An axe, a shovel, or anything." Shane (1953)
int i = 10;
"May the days be aimless. Let the seasons drift. Do not advance the action according to a plan."
Excellent example of the "real world", somebody in authority gives you an explicit requirement - "code something with as few lines as possible" - then (after the delivery) adds another requirement - "don't use goto".
When you point out that it was not part of the requirements you will be called unproffesional since "everybody knows" the second requirement is implicit in all projects.
Trying to anticipate all the possible implicit requirements will get you nowhere in fighting the "everybody knows" attitude. Your proffessor is an unreasonable customer. Unfortunately you just have to wear it because, (like many programmers in the "real world"), you don't have a boss with balls to set the customer straight.
Scope creep problems are akin to a builder being told the customer wanted an indoor swimming pool but neglected to say anything until after the building was finished. The builder will either prepare a quote for the new work or tell the customer to fuck off, why should software be any different?
And did you exchange a walk on part in the war for a lead role in a cage? - Pink Floyd.
The Y with diaresis is a convenience spelling of ij in Dutch. Try it out. It's easier writing a y with two dots than an i and a j seperately.
10 print "hello"
20 goto 10
Watch how fast that shit runs!
I hold very few opinions. I hold information based on observation and fact. If you wish to disagree, please use facts.
You should see the code that Pacbase creates. It's an application that writes COBOL with as many GOTOs as possible. It's horrendous! You are not supposed to look at the COBOL of course; you program with the Pacbase language which is almost as bad.
Alas, I can't put myself on that kind of level. And, in retrospect, if anyone put that code into one of my projects, I'd fire 'em too. Gratuitous recursion is too memory intensive and diffucult to read to be of much use. Sure it's pretty, but doing it with a simple loop is more efficient, even if oh so much uglier.
ad logicam Claiming a proposition is false because it was presented as the conclusion of a fallacious argument.
Oh brilliant!
Where was the 'flamebait' in that comment?
Idiot mods strike again.
I believe the teacher should gave students two pieces of code, one with spaguetti goto code, one with well behaved structured code.
Both of them big enough to not be trivial and both of them with some kind of bug.
"Please fix this one. It's called GT. If you solve it the qualification is 100%. If you're unable to fix it, fix the other one, called GTL (goto less), but the qualification in that case is 80%."
And then give 100% to any of the solutions.
That way they will learn WHY most goto's are a bad idea.
We are Turing O-Machines. The Oracle is out there.
But now most /. people read the article if it first shows up in digg.com !
We are Turing O-Machines. The Oracle is out there.
First of all, the term "order of magnitude" refers to power 10.
The term "order of magnitude" refers to whatever the speaker was referring to. Definitions of words and phrases are not set in stone. When talking about asymptotic bounds, people use "order of magnitude" all the time. Deal with it.