The only solution I can think of is creating a variable before the loop so it can enter the first time. However, I don't consider this as optimal.
In an interaction (shown through a sequence diagram) the natural way to support a loop is to use a combined fragment with the operand loop.
As said in formal/2017-12-05 §17.6.3.17 Loop (from page 584) :
The Guard may include a lower and an upper number of iterations of the loop as well as a Boolean expression. The semantics is such that a loop will iterate minimum the ‘minint’ number of times (given by the iteration expression in the
guard) and at most the ‘maxint’ number of times. After the minimum number of iterations have executed and the Boolean expression is false the loop will terminate.
Contrarily to a while in case of a do-while the test is at the end of the loop, an other way to say is the test (without side effect) is done at the beginning of the loop but its result is not taken into account the first time, and this is exactly the semantic of the combined fragment loop with ‘minint’ valuing 1 (but 0 in case of a while) and ‘maxint’ valuing * (means unlimited, see §17.6.4.9 page 586) => the notation for the loop operand is loop(1,*) and the Boolean expression is the test of the while.
The constraint in the loop fragment allows to write anything. Rather than using the contents of a variable you should express the number in clear text to explain the reason for the loop. In any case: graphical programming shall be avoided. Use it only to express some complex structures and not for each bit.
I'm taking a course on coursera that uses minizinc. In one of the assignments, I was spinning my wheels forever because my model was not performing well enough on a hidden test case. I finally solved it by changing the following types of accesses in my model
from
constraint sum(neg1,neg2 in party where neg1 < neg2)(joint[neg1,neg2]) >= m;
to
constraint sum(i,j in 1..u where i < j)(joint[party[i],party[j]]) >= m;
I dont know what I'm missing, but why would these two perform any differently from eachother? It seems like they should perform similarly with the former being maybe slightly faster, but the performance difference was dramatic. I'm guessing there is some sort of optimization that the former misses out on? Or, am I really missing something and do those lines actually result in different behavior? My intention is to sum the strength of every element in raid.
Misc. Details:
party is an array of enum vars
party's index set is 1..real_u
every element in party should be unique except for a dummy variable.
solver was Gecode
verification of my model was done on a coursera server so I don't know what optimization level their compiler used.
edit: Since minizinc(mz) is a declarative language, I'm realizing that "array accesses" in mz don't necessarily have a direct corollary in an imperative language. However, to me, these two lines mean the same thing semantically. So I guess my question is more "Why are the above lines different semantically in mz?"
edit2: I had to change the example in question, I was toting the line of violating coursera's honor code.
The difference stems from the way in which the where-clause "a < b" is evaluated. When "a" and "b" are parameters, then the compiler can already exclude the irrelevant parts of the sum during compilation. If "a" or "b" is a variable, then this can usually not be decided during compile time and the solver will receive a more complex constraint.
In this case the solver would have gotten a sum over "array[int] of var opt int", meaning that some variables in an array might not actually be present. For most solvers this is rewritten to a sum where every variable is multiplied by a boolean variable, which is true iff the variable is present. You can understand how this is less efficient than an normal sum without multiplications.
Hello is Go switch string just convenient form, but not fastest possible implementation?
switch s{
case "alpha": doalpha()
case "betta": dobetta()
case "gamma": dogamma()
default: dodefault()
Is this equal to:
if s=="alpha"{
doalpha()
} else if s == "betta" {
dobetta()
} else if s == "gamma" {
dogamma()
} else {
dodefault()
}
You;d have to benchmark it in order to tell the actual difference for your case. It depends on the compiler and the optimizations it does and thus on platform and architecture.
But see this link from the Go mailing list for some detail on implementation of the switch statement:
what is implemented is as follows.
in order, all non-constant cases are compiled and tested as if-elses.
groups of larger than 3 constant cases are binary divided and conquered.
3 or fewer cases are compared linearly.
So based on that there should be little if any difference. And the switch statement certainly looks cleaner. And it's the recommend way to write longer if-else statements:
It's therefore possible—and idiomatic—to write an if-else-if-else
chain as a switch.
In Go, a constant expression switch with 4 or more cases is implemented as a binary search.
The cases are sorted at compile time and then binary-searched.
In this small benchmark we can see that a switch with just 5 cases is on average 1.5 times faster than a corresponding if-then-else sequence. In general we can assume O(logN) vs. O(N) difference in performance.
3 of fewer cases are compared linearly, so expect the same performance as that of if-then-else.
I found the following code in my team's project:
Public Shared Function isRemoteDisconnectMessage(ByRef m As Message)
isRemoteDisconnectMessage = False
Select Case (m.Msg)
Case WM_WTSSESSION_CHANGE
Select Case (m.WParam.ToInt32)
Case WTS_REMOTE_DISCONNECT
isRemoteDisconnectMessage = True
End Select
End Select
End Function
Never mind that the function doesn't have a return type (I can easily add 'As Boolean'); what I'm wondering is, could there be any reason to prefer the above over the following (to me, much more readable) code?
Public Shared Function isRemoteDisconnectMessage(ByRef m As Message) As Boolean
Return m.Msg = WM_WTSSESSION_CHANGE AndAlso _
m.WParam.ToInt32() = WTS_REMOTE_DISCONNECT
End Function
To put the question in general terms: Does it make sense to use a switch (or, in this case, Select Case) block--and/or nested blocks--to test a single condition? Is this possibly faster than a straightforward if?
If you're worried about performance...profile. Otherwise you can't go wrong erring on the side of readability...
I don't believe it actually matters in terms of speed, the compiler should be able to optimize it.
I think it would just be a matter of preference.
My rule of thumb is to use a switch statement when the number of if/else conditions is greater than three. I don't have any data behind why this makes sense other than readability/maintainability seems to decrease as the number of if/else conditions increases.
I think the answer in the specific case you've given is no - it doesn't make sense, as suggested in other answers one would hope that the compilers would optimise away any practical differences.
I'd put money on this being a bit of cut, paste and delete coding - taking a generalised set of nested case statements and extracting that one bit that gives you the yes/no result you need.
If this were something similar in-line and/or there was a function call where the return flag is set then one might, possibly, be at a point where one could start to justify it but not as it is.
This question already has answers here:
Advantage of switch over if-else statement
(23 answers)
Eliminating `switch` statements [closed]
(23 answers)
Is there any significant difference between using if/else and switch-case in C#?
(21 answers)
Closed 2 years ago.
Why you would want to use a switch block over a series of if statements?
switch statements seem to do the same thing but take longer to type.
As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.
As an example, if you were doing:
int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}
This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.
Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.
Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)
If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.
Otherwise, stick with multiple if-else statements.
concerning Readability:
I typically prefer if/else constructs over switch statements, especially in languages that allows fall-through cases. What I've found, often, is as the projects age, and multiple developers gets involved, you'll start having trouble with the construction of a switch statement.
If they (the statements) become anything more than simple, many programmers become lazy and instead of reading the entire statement to understand it, they'll simply pop in a case to cover whatever case they're adding into the statement.
I've seen many cases where code repeats in a switch statement because a person's test was already covered, a simple fall-though case would have sufficed, but laziness forced them to add the redundant code at the end instead of trying to understand the switch. I've also seen some nightmarish switch statements with many cases that were poorly constructed, and simply trying to follow all the logic, with many fall-through cases dispersed throughout, and many cases which weren't, becomes difficult ... which kind of leads to the first/redundancy problem I talked about.
Theoretically, the same problem could exist with if/else constructs, but in practice this just doesn't seem to happen as often. Maybe (just a guess) programmers are forced to read a bit more carefully because you need to understand the, often, more complex conditions being tested within the if/else construct? If you're writing something simple that you know others are likely to never touch, and you can construct it well, then I guess it's a toss-up. In that case, whatever is more readable and feels best to you is probably the right answer because you're likely to be sustaining that code.
concerning Speed:
Switch statements often perform faster than if-else constructs (but not always). Since the possible values of a switch statement are laid out beforehand, compilers are able to optimize performance by constructing jump tables. Each condition doesn't have to be tested as in an if/else construct (well, until you find the right one, anyway).
However this isn't always the case, though. If you have a simple switch, say, with possible values of 1 to 10, this will be the case. The more values you add requires the jump tables to be larger and the switch becomes less efficient (not than an if/else, but less efficient than the comparatively simple switch statement). Also, if the values are highly variant ( i.e. instead of 1 to 10, you have 10 possible values of, say, 1, 1000, 10000, 100000, and so on to 100000000000), the switch is less efficient than in the simpler case.
Hope this helps.
Switch statements are far easier to read and maintain, hands down. And are usually faster and less error prone.
Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.
Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.
I personally prefer to see switch statements over too many nested if-elses because they can be much easier to read. Switches are also better in readability terms for showing a state.
See also the comment in this post regarding pacman ifs.
This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.
The question is how much is many?
Yesterday I was asking myself the same question:
public enum ProgramType {
NEW, OLD
}
if (progType == OLD) {
// ...
} else if (progType == NEW) {
// ...
}
if (progType == OLD) {
// ...
} else {
// ...
}
switch (progType) {
case OLD:
// ...
break;
case NEW:
// ...
break;
default:
break;
}
In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.
I ended up choosing the switch because it just reads better.
I have often thought that using elseif and dropping through case instances (where the language permits) are code odours, if not smells.
For myself, I have normally found that nested (if/then/else)s usually reflect things better than elseifs, and that for mutually exclusive cases (often where one combination of attributes takes precedence over another), case or something similar is clearer to read two years later.
I think the select statement used by Rexx is a particularly good example of how to do "Case" well (no drop-throughs) (silly example):
Select
When (Vehicle ¬= "Car") Then
Name = "Red Bus"
When (Colour == "Red") Then
Name = "Ferrari"
Otherwise
Name = "Plain old other car"
End
Oh, and if the optimisation isn't up to it, get a new compiler or language...
The tendency to avoid stuff because it takes longer to type is a bad thing, try to root it out. That said, overly verbose things are also difficult to read, so small and simple is important, but it's readability not writability that's important. Concise one-liners can often be more difficult to read than a simple well laid out 3 or 4 lines.
Use whichever construct best descibes the logic of the operation.
Let's say you have decided to use switch as you are only working on a single variable which can have different values. If this would result in a small switch statement (2-3 cases), I'd say that is fine. If it seems you will end up with more I would recommend using polymorphism instead. An AbstractFactory pattern could be used here to create an object that would perform whatever action you were trying to do in the switches. The ugly switch statement will be abstracted away and you end up with cleaner code.