Reputation: 63
I was wondering, which one is faster?
if else
statement select
from sql databaseFor example :
I have 2 variables and one condition
should I use :
if(a == 1 && b == 1) echo "abc";
OR
select * from table_name where (a==1 AND b == 1);
A reference from a journal or paper would be very helpful.
Upvotes: 0
Views: 80
Reputation: 95052
if(a == 1 && b == 1) echo "abc";
You have a and b in memory and check if they equal 1. If so take "abc" from memory and print. Done.
select * from table_name where (a==1 AND b == 1);
You sent the query to the database system. The database system makes a plan how to retrieve the data desired. It decides for a full table scan and reads record per record and compares a and b. Or it uses an index which it must read first, before being able to access the name table. For every record thus found it returns that record to the calling programm, i.e. copies the string to the calling app's memory.
Of course the first method is much, much faster.
However, I suppose what you want to ask is: Which is faster: To use a database to store names, or have thousands of lines like if(a == 1 && b == 1) echo "abc";
, if(a == 1 && b == 2) echo "def";
etc.?
For every name asked you would have to execute line per line until finally you found your match. The database system on the other hand might use an index so it would find the name rather quickly. However there is still the process of your programm having to talk with the dbms and records to read physically probably. So it actually depends on your configuration (in-memory database? millions of records? ...)
EDIT: Just as a sidenote: You would usually not use thousands of lines like if(a == 1 && b == 1) echo "abc";
, but use a two-dimensional array: print name[a][b];
.
Upvotes: 3
Reputation: 5835
Obviously Sql Statement is a LOT slower than if..else..
Sql statement requires parsing your request, accessing the disk and a lot more where if..else is merely a branch.
although if a & b are not integers but some complex type with operator overloading where the operator sleeps for a few seconds, just for fun, then sql statement would be faster.
Upvotes: 0