Does ternary operator enhance speed of execution? [duplicate] - operators

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Speed difference between If-Else and Ternary operator in C…?
This is a very simple question, does the ternary operator increase the speed of execution in comparison to if else statement?

No. Most languages parse it to a very similar syntax tree. Any jit/optimizer is going to collapse it into 'basic blocks' of simple instructions without jumps; and from that point on it will optimize the same.
There could, of course, be some really bad systems out there for which this is not true; but gcc/msvc/c# will all deal with it equally well.
It's abundance can usually be associated with the fact that it is an expression instead of just a logic statement. This makes it all to easy to do things like (note: really ugly example ahead):
size_t n = strlen( pszVar == NULL ? "" : pszVar );

Related

SQL Server: Canonical way to get a substring from a particular index to the end of the string? [duplicate]

This question already has answers here:
How do I remove the first characters of a specific column in a table?
(12 answers)
Closed 5 years ago.
In SQL Server, given a string, is there an established, canonical "best" way to get a substring starting at a particular index, and continuing to the end of the string?
"Best" here means a balance of the following considerations:
Most efficient performance-wise
Easiest for developers to read and understand
Shortest / easiest to remember without having to look up the syntax
Ways I've come across to do this, using 2 in these examples as the index from which to start the substring:
SUBSTRING(mystring, 2, 1000000)
Source: https://stackoverflow.com/a/8302533/12484
Con: The use of the "magic number" 1000000 (which could be any "sufficiently large" value) seems not ideal.
Con: What my code encounters a string that is longer than that value?
.
SUBSTRING(mystring, 2, 2147483647)
Con: There's no built-in constant that we can substitute for that "max int" value.
Con: That "max int" value is hard to remember, and is annoying to have to Google every time.
Con: Even assuming we're talking about an varchar(max) or nvarchar(max), the string length might possibly exceed that size, depending on the SQL Server version?
.
SUBSTRING(mystring, 2, LEN(mystring) - 2 + 1)
Con: This syntax is somewhat cumbersome.
.
RIGHT(mystring, LEN(mystring) - 2 + 1)
Con: This is still is fairly cumbersome.
.
SUBSTRING(mystring, 2, LEN(mystring))
Con: Per the docs, it's okay for the "length" parameter to have a value that goes past the end of the string, but this might initially seem like a possible index-out-of-range bug to developers reading this code (until they also look up the docs and see that this approach is ok)?
Is there a better general solution to this problem, taking into account the considerations that I mentioned above (performance, readability, ease of use)?
As I mentioned in the comment, another option you could use is
STUFF(mystring, 1,2,'')
This should be easy to understand and remember for developers.
SUBSTRING(mystring, 2, LEN(mystring) - 2 + 1)
This would definitely be my preferred way to do it. Even if "canonically" you can extend beyond the bounds of the string's length in a SUBSTRING() function, its better not to. If you are concerned about confusions with the syntax, simply preface the line with a comment explaining. In fact, I would probably preface a this kind of operation with a comment anyway to explain why I am using a substring and what I anticipate the substring to consist of

Which approach is better - CASE WHEN or DECODE [duplicate]

This question already has answers here:
CASE vs. DECODE
(7 answers)
Closed 6 years ago.
For some simple logical tests the same functionality can be achieved with CASE WHEN and DECODE syntax. What approach is better here (argumentation/measurement needed)?
SUM(CASE WHEN xyz=100 THEN 1 ELSE 0 END)
or
SUM(DECODE(xyz,100,1,0))
Recently I stumbled upon this: https://community.oracle.com/thread/1112467?tstart=0
"The performance difference is so slight that it makes very little sense in using that as primary criteria for whether to use CASE or DECODE. So unless you're calling this statement from a very tight loop doing millions of iterations, the decision should rather be which one, CASE or DECODE, best suits the need."

Why does comparing integers with Equal(=) takes 800ms more that using GreaterThan(>) and LessThan(<) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Using Linq and EntityFramework we recently noticed, while testing our queries performances, that the use of Equal(=) operator to compare two integers takes around 800ms more than using a combination of GreaterThan(>) and LessThan(<) operators.
So basically, replacing itemID == paramID (Both being integers) by !(itemID > param ID || itemID < paramID) in our linq query makes the query faster by about 800ms consistently.
Anyone with a deep knowledge of SQL could explain this result to me?
If this was always faster SQL Server would do the rewrite for you. It does not so you can conclude that it is not always faster to do this. In fact it is a bad idea to do this rewrite in 99.999% of the cases.
The information given in the question (almost none) does not allow for further analysis.
Often people ask "why did this random change make my query faster". The answer is always: You accidentally triggered a better query plan. There is no system to it. Query plans can be unstable.
Psychic guess: The complex predicate forces a table scan (or makes it appear better) than using an index. That can sometimes be a good thing.
The first step would be to examine the generated sql. My guess is itemID is nullable and EntityFramework's default behaviour with nullable properties isn't the greatest. It will translate your query into something like: prop = value OR prop is null
If that is the case and you are using EF6, you can overide that behaviour by:
context.UseDatabaseNullSemantics = true;
Msdn

What's best style? '<>' or 'not =' / VBA [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
I was under the impression that it was always best to write:
If Not X = Y then
then
If X <> Y then
but I'm not sure where I did I get this idea:-).
Is there a best? Why do we have two way to do the same thing anyways?
tks!
Readability is most important.
The second seems more natural to me. It seems misleading to use the equal sign and then adding the Not to it.
The Not IMHO is best used with boolean functions like IsNumeric(...) which lends itself to a more natural reading of the code, E.g.,
If Not IsNumeric(myNumberString) Then
And, I personally prefer using Not to = False for Boolean tests. E.g., I like...
If bFlag1 Then
If Not bFlag2 Then
...more than...
If bFlag1 = True Then ' <-- (This is totally redundant) = True
If bFlag2 = False Then
If a <> b = True Then ' <-- please don't ever do this
The first option is to be avoided as confusing. Someone might think that you meant to write If (Not X) = Y Then.
Why do we have two ways? Because... how could you prevent it? It's a natural consequence of having the three operators =, <>, and Not.
Besides style and readabilty there is a little difference:
Not is a logical operator and <> is a relational operator and logical and bitwise operators have a lower precedence than other arithmetic and relational operators (see here).
Furthermore the Not operator can be overloaded, I think this is not possible for relational operators in VBA.
I think that If X <> Y Then... is more expressive (but this is a matter of preference). Also it might be more efficient in terms of condition evaluation, since If Not X = Y Then... needs two operations (evaluating the equality and negating the result) rather than one. But, with some code optimisation behind the scene, who knows what actually happens?...
However, there are cases when is impossible to avoid the negated condition; for example the Is operator does not have a negated form (like Isn_t or something), so in this case you need to say If Not X Is Y Then...

Why would a sql query have "where 1 = 1" [duplicate]

This question already has answers here:
Closed 14 years ago.
I was going through a few queries I am maintaining, and a programmer had put in the queries "where 1=1" to me that always seems to evaluate to true.
Are there benefits to this?
Duplicate: Why would someone use WHERE 1=1 AND in a SQL clause?
That question isn't an answer to this question.
Where-clause:
select * from table where 1=1 and sStatus not in ('status1','status2','status3')
No programming or if statements to push an and in there. A straight query.
If you could un-close this, I would like to know whether there is a purpose so that I may rewrite and remove the 1=1 if it is unnecessary.
Was it dynamic queries? Sometimes that's helpful when building dynamic queries based on parameters that are optional.
If you automatically want to add restrictions to your query, it makes your life easier:
string sql = "SELECT * FROM table WHERE 1=1";
if (someflag) {
sql += " AND valid = 1";
}
if (someotherflag) {
sql += " AND special = 1";
}
execute(sql);
Without WHERE 1 = 1 you would in each case have to check if it's the first restriction you add (and then use WHERE ...) or if you already added some other restriction before (and then add AND ...).
If you are dynamically building a where clause, you can be a bit lazy and assume that every clause you add can be prefixed with "AND", e.g.
$str="select foo from bar where 1=1";
if ($filter1)
{
$str.=" and col1='frobozz'";
}
I use this for dynamic where clauses when I'm doing some lazy programming and don't want to always check if the clause is empty to determine if I now need an "AND" between my dynamic clauses.
This really only makes sense in dynamic queries. If you are adding parameters in a loop instead of having to check if there is a WHERE already you can just append AND Column = Value every time.
I've seen two reasons for this, when you always want a true result, or when there is going to be an arbitrary number of "and condition = value" appended to the statement
That is very interesting... The WHERE clause contains nothing but 1=1? I have seen this frequently in SQL injection attempts in which the WHERE clause is set to
xyz="something" OR 1=1;
as a means to always return a list of results.
Can you tell us more about what is going on with this query so we might be able to answer the question better?
Nicholas