How do I evaluate boolean expression with many arguments? - java

I am trying to set up a condition check for my code. However, the code has become long and complex. I need a simpler version of the code that can easily do the job.
I have tried to compare three boolean values separated by brackets such that I only compare two values.
if (
(((userState[0][0]&&userState[0][1])&&(userState[0][2]))) ||
(((userState[1][0]&&userState[1][1])&&(userState[1][2]))) ||
(((userState[2][0]&&userState[2][1])&&(userState[2][2]))) ||
(((userState[0][0]&&userState[1][0])&&(userState[2][0]))) ||
(((userState[0][1]&&userState[2][1])&&(userState[1][1]))) ||
(((userState[0][2]&&userState[2][2])&&(userState[1][2]))) ||
(((userState[0][0]&&userState[2][2])&&(userState[1][1]))) ||
(((userState[1][2]&&userState[1][1])&&(userState[2][0])))
)

You can use nested loop:
boolean result;
for (int i = 0; i < userState.length; i++) {
for (int j = 0; j < userState[i].length; j++) {
result |= userStage[i][j];
}
}

Clean code suggests to never write such code in the first place.
If at all, you could for example create small helper methods for each line, like:
private hasStateConditionXyz(boolean[][] userState) {
return userState[0][0]&&userState[0][1])&&(userState[0][2];
}
where "Xyz" would be a nice handsome name that tells the reader what the intention of that check is.
Of course, that breaks your ability to somehow loop over your array.
In other words:
if possible, see if it is possible to compute your result by looping over that array, instead of writing down such manual "patterns"
if not, consider using such named helper methods
Where, in the end, the real answer might be to step back and look at the overall problem to solve. Meaning: when you have such a complex "state machine", then it might be better to really create a state machine. Or to use some sort of "work flow" engine. Such tools allow you to express such complex (business?) rules in much more concise and readable ways.

Related

Nested ifs or ands?

I'm a beginner level programmer who's just starting to work on actual projects, and I'm starting to think about things such as efficiency and if my code looks professional. I was wondering if, when trying to check multiple booleans, is it better to use nested if statements, or multiple && and || operators.
Action action = event.getAction();
Material holding = event.getItem().getType();
if((action.equals(Action.RIGHT_CLICK_AIR)||(action.equals(Action.RIGHT_CLICK_BLOCK))))
{
if((event.hasItem())&&(holding.equals(Material.COMPASS)))
{
//if the player right clicked while holding a compass
}
}
Does this look right? I tried to group the like if-statements together. Also, if there's anything else I can do to improve my formatting, please tell me! Thanks.
Welcome to the Stack Overflow community!
There is no problem with the code shared in the question. In some cases, it is better to opt for legibility so that your co-workers will be able to understand the proposed code better. But in the end, this is very subjective.
IMHO, it is easier to understand if we write all the conditions at once. So,
Action action = event.getAction();
Material holding = event.getItem().getType();
Boolean isRequiredAction = action.equals(Action.RIGHT_CLICK_AIR) || action.equals(Action.RIGHT_CLICK_BLOCK)
if (
isRequiredAction
&& event.hasItem()
&& holding.equals(Material.COMPASS)
)
{
// logic...
}
However, if you really want advice and tips on how to refactor it and best practices in a particular language, try Code Review community.
imo for a personal taste, i would put those nested conditions in a boolean variable that can explain the behavior as much as the comment you let in the block, like:
boolean isActionRightClick = action.equals(Action.RIGHT_CLICK_AIR ||action.equals(Action.RIGHT_CLICK_BLOCK);
boolean isHoldingACompass = event.hasItem() && holding.equals(Material.COMPASS);
and then
if ( isActionRightClick && isHoldingACompass ) {...}
Yes your code looks very good to me. I used to work on big projects and uses nested if statements, or multiple && and || operators which saves time. In your code efficiency can be traced at :
if((action.equals(Action.RIGHT_CLICK_AIR)||(action.equals(Action.RIGHT_CLICK_BLOCK))))
As now check only one condition in the or statement will satisfy the if condition which will save time and also shorten the code length.
You can make this code more shorter by removing unwanted parenthesis from your code. Which you must take care in future.
For more details related to efficient coding you can visit this link:
https://docs.oracle.com/cd/E80738_01/pt854pbh2/eng/pt/tpcd/task_WritingMoreEfficientCode-0749ba.html#topofpage
This is good to think about the quality/readability of your code.
Nested "if" are a good question in most of the case i think this depends of people. Some people prefer to nest it, to evaluate condition one after another. Some other prefer to not nest for not lose the track in the block.
But in most of the case be careful to not do to much if statement and try to replace it with pattern design (Easier said than done.). You can find a lot of it in java-design-patterns
I think you could make it even more shorter by using ternary operator (?:) right.
if (expression1) {
result = 1;
} else if (expression2) {
result = 2;
} else if (expression3) {
result = 3;
} else {
result = 0;
}
result = (expression1) ? 1 : (expression2) ? 2 : (expression3) ? 3 : 0;

Is the Java method "Arrays.deepToString()" the most efficient way to print a 2D array?

I've found similar questions like so:
Java - Best way to print 2D array?
But they don't answer the question of- Is it more efficient?
I'm writing a basic little console game in C# that requires repeatedly clearing and writing to the console in order to refresh the game state. In searching for a more efficient way to do this than my current attempt, iterating through the array with a nested for loop and printing it that way, I found this in Java:
Arrays.deepToString(arrayName);
which does what I'm trying to achieve.
Is this more efficient than using nested loops in Java like so?:
String[][] map = new String[10][10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
map[i][j] = "=";
}
}
boolean firstRun = true;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j == 0 && firstRun == false)
{
System.out.print("\n");
}
System.out.print(map[i][j]);
firstRun = false;
}
}
If it is more efficient, is there a C# library equivalent? I can't seem to find one or even someone asking about one anywhere.
You are looking at this from the wrong angle:
your code is dealing with almost no data (10x10 is nothing in 2019)
your code is doing console output
Rest assured: printing to stdout like this is many times more expensive than processing a close-to-nothing array in memory (see here for some example data).
Thus, the real answer is: you can safely ignore performance aspects here.
Instead invest your time into writing code that is easy to read, understand, and maintain. Coming from there, that single call to Arrays.deepToString(arrayName); is very much to be preferred over writing custom loops doing the same.
Keep in mind: in the java world, runtime performance doesn't come out of writing "clever" source code. It comes out of the JIT deciding "this code is used so often, I should translate it to machine code". If the JIT thinks "not worth optimising" then it is not worth optimising. If it is worth optimising, make that easy for the JIT. By writing simple and easy code.
Long story short: it is a nice exercise to implement that functionality, but now that you achieved that, throw it away and use the library call that works for you.

What is the best way to exit loop in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What is the best way to end a loop in Java?
This:
boolean exit = false;
while((a < 5) && (exit = false)){
if(a == 3)
exit = true;
else
a++;
}
Or this:
while((a < 5){
if(a == 3)
break;
else
a++;
}
Some people may find that break are harder to debug (personally, I prefer using flag) but it is principally a matter of opinion.
Imagine a loop body which contains over 500 lines of code, with some break statements located everywhere, it may be harder for you to visualise all the possibilities of exiting the loop.
Another reason of why I like using a flag is that you can give a signifiant name to the ending point instead of simply break.
Note that you can also use a flag in a for loop example :
boolean flag = false;
for(int i = 0; !flag && i < 10; i++) {
// some treatment
}
It may be interesting however, to know that when dealing with loop, there is the continue keyword which allow you to not exit the loop, but skip directly to the next iteration.
What is the best way to finish a loop in Java?
If there was really a best way between both, Java would probably not allow the other ;)
I guess the most important is to use the same convention as your co-worker so the code does not differ from class to class.
break exist for a reason, right!
while(a < 5){
if(a == 3)
break;
else
a++;
}
Very simple answer, go for the break, less flags, less to debug, easier to maintain. It is simple to change from a while to for loop without any modifications in the logic. Think of a scenario where you would need to add more conditions...
My opinion is if you don't understand the usage of break and continue then you might go for the flag all the time. But there is not only one answer. Your question is what option is better for exit the loop and from your two examples the option is simple. My opinion is the break one.
Now some will use the flag, and some the break, and they give code samples for which will fit better. But this is not your question!
I can give you lots of examples, where some I would go for the flag and other for the break and some a mix of both. It depends on what my loop is about to handle.
break is to mark that if we reach this condition, we will go out of the loop emiditely. Which is very important in some loop logic.
Even though when you/co-worker add more logic, before or after that condition, still the loop will exit where it reaches the break.
Sometimes you maybe want to flag that you reached a condition but want still to go thru all the instructions the loop covers, and here does a bool help you to stop the loop but after it went thru all the logic.
If you don't use flag/break in a right way your system can act very strange, specially when adding new logic.
Remember that you also can use break and continue with a label, which is not so common but good to know.
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
The first snippet is syntactically wrong - = is the assignment operator. You were looking for the equality operator, ==:
while ((a < 5) && (exit == false)) {
Or better yet, since exit is a boolean, just evaluate it directly:
while (a < 5 && !exit) {
Other than that, you should always strive to follow the convention of the project you're working on. If it's coding styles prefers breaks - just use them. If it prohibits them, don't.
Once you throw project guideline considerations out the window, it's completely a matter of preference. Personally, I tend to prefer the break statement, especially if I have several conditions to evaluate. E.g.:
while (a < 5) {
// do stuff
if (a == 3) {
break;
}
// do more stuff
if (b >= 19) {
break;
}
// etc...
}
But ultimately, you should evaluate it on a case-to-case basis. Preferring breaks, like I do, doesn't mean you should blindly always use them. Choose whatever makes the code look better and easier to maintain.
I depends on what you mean by "best" ? With the break, you exit the loop early, so that is more efficient.
I would prefer the first, cause goto is considered harmful. And an exit is like a goto. But more important: Please always use {} when writing a if clause.
Also, when using a condition, give it a name. It is almost simpler to understand ageBelow18 instead of today.getYear() < customer.getBirthday().getYear(); (the code is not correct, I know).
Both those options you have presented aren't as good as two alternatives.
Seeing as you directly exit the loop after a simple comparison then the best option is:
while (a < 5 && a != 3) {
a++;
}
This is because you need to check both conditions before executing the body, and you don't need to do anything special when exiting the loop.
However, if you need to do need a bit of special logic when a certain condition is hit then you should use a while true loop and breaks.
while (true) {
if (a >= 5) {
break; // nothing special, just exit
} else if (a == 3) {
a *= 2; // double a before exiting loop
break;
}
a++;
}
The while (true) shows that the only way to exit the loop is with a break, so the programmer should keep an eye out for them. The breaks should also be grouped together at the top of the loop body, so they act as guards preventing the loop body from being executed if their condition is hit.
I would choose the break statement since:
Code is more clean
No need for extra code declarations
Debug the code is easier
It's common to mess with a lot of flags declared on the condition. You will not want to get a lot of nested conditions on the same line.
There is also exist the continue keyword that will let you to skip parts of the code if necessary.

Is it bad practice to use break to exit a loop in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I was wondering if it is a "bad practice" to use a break statement to exit a loop instead of fulfilling the loop condition?
I do not have enough insight in Java and the JVM to know how a loop is handled, so I was wondering if I was overlooking something critical by doing so.
The focus of this question: is there a specific performance overhead?
Good lord no. Sometimes there is a possibility that something can occur in the loop that satisfies the overall requirement, without satisfying the logical loop condition. In that case, break is used, to stop you cycling around a loop pointlessly.
Example
String item;
for(int x = 0; x < 10; x++)
{
// Linear search.
if(array[x].equals("Item I am looking for"))
{
//you've found the item. Let's stop.
item = array[x];
break;
}
}
What makes more sense in this example. Continue looping to 10 every time, even after you've found it, or loop until you find the item and stop? Or to put it into real world terms; when you find your keys, do you keep looking?
Edit in response to comment
Why not set x to 11 to break the loop? It's pointless. We've got break! Unless your code is making the assumption that x is definitely larger than 10 later on (and it probably shouldn't be) then you're fine just using break.
Edit for the sake of completeness
There are definitely other ways to simulate break. For example, adding extra logic to your termination condition in your loop. Saying that it is either loop pointlessly or use break isn't fair. As pointed out, a while loop can often achieve similar functionality. For example, following the above example..
while(x < 10 && item == null)
{
if(array[x].equals("Item I am looking for"))
{
item = array[x];
}
x++;
}
Using break simply means you can achieve this functionality with a for loop. It also means you don't have to keep adding in conditions into your termination logic, whenever you want the loop to behave differently. For example.
for(int x = 0; x < 10; x++)
{
if(array[x].equals("Something that will make me want to cancel"))
{
break;
}
else if(array[x].equals("Something else that will make me want to cancel"))
{
break;
}
else if(array[x].equals("This is what I want"))
{
item = array[x];
}
}
Rather than a while loop with a termination condition that looks like this:
while(x < 10 && !array[x].equals("Something that will make me want to cancel") &&
!array[x].equals("Something else that will make me want to cancel"))
Using break, just as practically any other language feature, can be a bad practice, within a specific context, where you are clearly misusing it. But some very important idioms cannot be coded without it, or at least would result in far less readable code. In those cases, break is the way to go.
In other words, don't listen to any blanket, unqualified advice—about break or anything else. It is not once that I've seen code totally emaciated just to literally enforce a "good practice".
Regarding your concern about performance overhead, there is absolutely none. At the bytecode level there are no explicit loop constructs anyway: all flow control is implemented in terms of conditional jumps.
The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.
However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.
If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.
However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.
In my opinion a For loop should be used when a fixed amount of iterations will be done and they won't be stopped before every iteration has been completed. In the other case where you want to quit earlier I prefer to use a While loop. Even if you read those two little words it seems more logical. Some examples:
for (int i=0;i<10;i++) {
System.out.println(i);
}
When I read this code quickly I will know for sure it will print out 10 lines and then go on.
for (int i=0;i<10;i++) {
if (someCondition) break;
System.out.println(i);
}
This one is already less clear to me. Why would you first state you will take 10 iterations, but then inside the loop add some extra conditions to stop sooner?
I prefer the previous example written in this way (even when it's a little more verbose, but that's only with 1 line more):
int i=0;
while (i<10 && !someCondition) {
System.out.println(i);
i++;
}
Everyone who will read this code will see immediatly that there is an extra condition that might terminate the loop earlier.
Ofcourse in very small loops you can always discuss that every programmer will notice the break statement. But I can tell from my own experience that in larger loops those breaks can be overseen. (And that brings us to another topic to start splitting up code in smaller chunks)
Using break in loops can be perfectly legitimate and it can even be the only way to solve some problems.
However, it's bad reputation comes from the fact that new programmers usually abuse it, leading to confusing code, especially by using break to stop the loop in conditions that could have been written in the loop condition statement in the first place.
No, it is not a bad practice to break out of a loop when if certain desired condition is reached(like a match is found). Many times, you may want to stop iterations because you have already achieved what you want, and there is no point iterating further. But, be careful to make sure you are not accidentally missing something or breaking out when not required.
This can also add to performance improvement if you break the loop, instead of iterating over thousands of records even if the purpose of the loop is complete(i.e. may be to match required record is already done).
Example :
for (int j = 0; j < type.size(); j++) {
if (condition) {
// do stuff after which you want
break; // stop further iteration
}
}
It isn't bad practice, but it can make code less readable. One useful refactoring to work around this is to move the loop to a separate method, and then use a return statement instead of a break, for example this (example lifted from #Chris's answer):
String item;
for(int x = 0; x < 10; x++)
{
// Linear search.
if(array[x].equals("Item I am looking for"))
{
//you've found the item. Let's stop.
item = array[x];
break;
}
}
can be refactored (using extract method) to this:
public String searchForItem(String itemIamLookingFor)
{
for(int x = 0; x < 10; x++)
{
if(array[x].equals(itemIamLookingFor))
{
return array[x];
}
}
}
Which when called from the surrounding code can prove to be more readable.
There are a number of common situations for which break is the most natural way to express the algorithm. They are called "loop-and-a-half" constructs; the paradigm example is
while (true) {
item = stream.next();
if (item == EOF)
break;
process(item);
}
If you can't use break for this you have to repeat yourself instead:
item = stream.next();
while (item != EOF) {
process(item);
item = stream.next();
}
It is generally agreed that this is worse.
Similarly, for continue, there is a common pattern that looks like this:
for (item in list) {
if (ignore_p(item))
continue;
if (trivial_p(item)) {
process_trivial(item);
continue;
}
process_complicated(item);
}
This is often more readable than the alternative with chained else if, particularly when process_complicated is more than just one function call.
Further reading: Loop Exits and Structured Programming:
Reopening the Debate
If you start to do something like this, then I would say it starts to get a bit strange and you're better off moving it to a seperate method that returns a result upon the matchedCondition.
boolean matched = false;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(matchedCondition) {
matched = true;
break;
}
}
if(matched) {
break;
}
}
To elaborate on how to clean up the above code, you can refactor, moving the code to a function that returns instead of using breaks. This is in general, better dealing with complex/messy breaks.
public boolean matches()
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(matchedCondition) {
return true;
}
}
}
return false;
}
However for something simple like my below example. By all means use break!
for(int i = 0; i < 10; i++) {
if(wereDoneHere()) { // we're done, break.
break;
}
}
And changing the conditions, in the above case i, and j's value, you would just make the code really hard to read. Also there could be a case where the upper limits (10 in the example) are variables so then it would be even harder to guess what value to set it to in order to exit the loop. You could of course just set i and j to Integer.MAX_VALUE, but I think you can see this starts to get messy very quickly. :)
No, it is not a bad practice. It is the most easiest and efficient way.
While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.
If you know in advance where the loop will have to stop, it will probably improve code readability to state the condition in the for, while, or `do-while loop.
Otherwise, that's the exact use case for break.
break and continue breaks the readability for the reader, although it's often useful.
Not as much as "goto" concept, but almost.
Besides, if you take some new languages like Scala (inspired by Java and functional programming languages like Ocaml), you will notice that break and continue simply disappeared.
Especially in functional programming, this style of code is avoided:
Why scala doesn't support break and continue?
To sum up: break and continueare widely used in Java for an imperative style, but for any coders that used to practice functional programming, it might be.. weird.

Is the ternary operator faster than an "if" condition in Java [duplicate]

This question already has answers here:
Which "if" construct is faster - statement or ternary operator?
(6 answers)
Closed 6 years ago.
I am prone to "if-conditional syndrome" which means I tend to use if conditions all the time. I rarely ever use the ternary operator. For instance:
//I like to do this:
int a;
if (i == 0)
{
a = 10;
}
else
{
a = 5;
}
//When I could do this:
int a = (i == 0) ? 10:5;
Does it matter which I use? Which is faster? Are there any notable performance differences? Is it a better practice to use the shortest code whenever possible?
Does it matter which I use?
Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.
Which is faster?
Neither.
Is it a better practice to use the shortest code whenever possible?
Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).
If there's any performance difference (which I doubt), it will be negligible. Concentrate on writing the simplest, most readable code you can.
Having said that, try to get over your aversion of the conditional operator - while it's certainly possible to overuse it, it can be really useful in some cases. In the specific example you gave, I'd definitely use the conditional operator.
Ternary Operator example:
int a = (i == 0) ? 10 : 5;
You can't do assignment with if/else like this:
// invalid:
int a = if (i == 0) 10; else 5;
This is a good reason to use the ternary operator. If you don't have an assignment:
(i == 0) ? foo () : bar ();
an if/else isn't that much more code:
if (i == 0) foo (); else bar ();
In performance critical cases: measure it. Measure it with the target machine, the target JVM, with typical data, if there is a bottleneck. Else go for readability.
Embedded in context, the short form is sometimes very handy:
System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ());
Yes, it matters, but not because of code execution performance.
Faster (performant) coding is more relevant for looping and object instantiation than simple syntax constructs. The compiler should handle optimization (it's all gonna be about the same binary!) so your goal should be efficiency for You-From-The-Future (humans are always the bottleneck in software).
The answer citing 9 lines versus one can be misleading: fewer lines of code does not always equal better.
Ternary operators can be a more concise way in limited situations (your example is a good one).
BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!
Also consider future maintainability, if-else is much easier to extend or modify:
int a;
if ( i != 0 && k == 7 ){
a = 10;
logger.debug( "debug message here" );
}else
a = 3;
logger.debug( "other debug message here" );
}
int a = (i != 0 && k== 7 ) ? 10 : 3; // density without logging nor ability to use breakpoints
p.s. very complete StackOverflow answer at To ternary or not to ternary?
Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.
Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null is supplied for a parameter value.
For example:
public void myMethod(int par1, String optionalPar2) {
String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}
In the above example, passing null as the String parameter value gets you a default string value instead of a NullPointerException. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Moreover, this pattern enables you to make the String parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:
public void myMethod(int par1) {
return myMethod(par1, null);
}
It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.
In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.
For the example given, I prefer the ternary or condition operator (?) for a specific reason: I can clearly see that assigning a is not optional. With a simple example, it's not too hard to scan the if-else block to see that a is assigned in each clause, but imagine several assignments in each clause:
if (i == 0)
{
a = 10;
b = 6;
c = 3;
}
else
{
a = 5;
b = 4;
d = 1;
}
a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6 : 4;
c = (i == 0) ? 3 : 9;
d = (i == 0) ? 12 : 1;
I prefer the latter so that you know you haven't missed an assignment.
Try to use switch case statement but normally it's not the performance bottleneck.

Categories

Resources