Domanda

Looking at some pieces of code around the internet, I've noticed some authors tend to write string comparisons like

if("String"==$variable)

in PHP, or

if("String".equals(variable))

Whereas my preference is:

if(variable.equals("String"))

I realize these are effectively equal: they compare two strings for equality. But I was curious if there was an advantage to one over the other in terms of performance or something else.

Thank you for the help!

È stato utile?

Soluzione

One example to the approach of using an equality function or using if( constant == variable ) rather than if( variable == constant ) is that it prevents you from accidentally typoing and writing an assignment instead of a comparison, for instance:

if( s = "test" )

Will assign "test" to s, which will result in undesired behaviour which may potentially cause a hard-to-find bug. However:

if( "test" = s )

Will in most languages (that I'm aware of) result in some form of warning or compiler error, helping to avoid a bug later on.

Altri suggerimenti

With a simple int example, this prevents accidental writes of

if (a=5)

which would be a compile error if written as

if (5=a)

I sure don't know about all languages, but decent C compilers warn you about if (a=b). Perhaps whatever language your question is written in doesn't have such a feature, so to be able to generate an error in such a case, they have reverted the order of the comparison arguments.

Yoda conditions call these some.

The kind of syntaxis a language uses has nothing to do with efficiency. It is all about how the comparison algorithm works.

In the examples you mentioned, this:

if("String".equals(variable))

and this:

if(variable.equals("String"))

would be exactly the same, because the expression "String" will be treated as a String variable.

Languages that provide a comparison method for Strings, will use the fastest method so you shouldn't care about it, unless you want to implement the method yourself ;)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top