Switch is faster than If?
#1

Hi bro's!


Which of these two is faster ?

PHP код:
if(var == 1) { return X; } 
or

PHP код:
switch(var) { case 1: return X; } 
? and why?


And.. how can i do my own benchmark?


Thank you!
Reply
#2

https://sampforum.blast.hk/showthread.php?tid=218491
Reply
#3

No matter which one is faster, don't use switch in such a situation.

Anyways, you can do benchmarks by running both very often, saving the start time and comparing it to the end time.
Reply
#4

Example:

I Have a JOB System.

for this:
PHP код:
if(JOB == 1) return SendClientMessage(playerid, -1"PizzaBoy");
if(
JOB == 2) return SendClientMessage(playerid, -1"Fisherman");
if(
JOB == 3) return SendClientMessage(playerid, -1"Lumberjacker");
if(
JOB == 4) return SendClientMessage(playerid, -1"Seller"); 
can i use this:
PHP код:
switch(JOB)
{
case 
1SendClientMessage(playerid, -1"PizzaBoy");
case 
2SendClientMessage(playerid, -1"Fisherman");
case 
3SendClientMessage(playerid, -1"Lumberjacker");
case 
4SendClientMessage(playerid, -1"Seller");

right?
Reply
#5

Switch and if got their own usage.
If you use if in switch place it will be slow and if you use switch in if place it will be slow.

How?
Lets say you need to check for 1 and 3000 by switch you do
PHP код:
switch(var)
{
    case 
1..3000:
    {
    }
    default:
    {
    }

At this case switch used in if place and will be slow so have to use
PHP код:
if(< var < 3001)
{


So we get to this point switch is faster when switch is needed ( your above post declears switch example )
And if is faster when if is needed.
Reply
#6

So..

i know if usage, but sometimes i can use switch in place of if (like my example above) and both of these two have same ticktime to process, right?
Reply
#7

Quote:
Originally Posted by rolex
Посмотреть сообщение
So..

i know if usage, but sometimes i can use switch in place of if (like my example above)
exactly D:
Quote:
Originally Posted by rolex
Посмотреть сообщение
both of these two have same ticktime to process, right?
Didn't get what you mean : o, mind explaining?
Reply
#8

In my example above, switch and if have same benchmark!?
Reply
#9

why worry about this not real problem? did you profile to see that this was the real problem? no i bet you dont! other code is a problem not this so do not worry
Reply
#10

This is not a "problem" for me, and i never said that.

It's just a question, and aswered!


Thank you'all.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)