What is the difference between Operator and Method?
Femaref's answer is pretty good; I would like to expand it.
Operators (usually) is rigidly connected to the language: things such as +
, -
, *
and /
, as a rule, directly translated by the compiler into machine language (if the main mechanism for this language system) without the need to explicitly call the method in the library. So it is / was in C, for example. If these operators have not been defined in the language, you will need to code plus(2,2)
instead 2 + 2
.
Operators defined in the language take advantage of built-in precedence. *
and /
usually have a higher priority than +
and -
, so you can write 3 * 3 + 4 * 4
and get 25, not 52 or 84, which you get without prioritization or different priorities.
The line turns a little gray when the statements are recognized by the compiler but still delegated to the library. Complex numbers in FORTRAN can be an example: often the compiler does not want to directly compile complex operations to machine code, but will generate machine code to call the library.
Most people only think of arithmetic operators like +
, -
etc. But you can also consider the square brackets ( [ ]
) operator for array indexing, for example.
Some languages allow you to overload their operators, so you can replace the method call with what the operator would normally do.
Most languages do not allow you to define your own operators, which support the same mechanisms as the built-in ones. Scala is an exception; you can define an operator +++
if you like and hook it up to the way you provide. Some people think that operator overloading makes the code difficult to understand, so the jury still doesn't know if it's a good idea.
a source to share
In C and Java, you cannot override the "+" operator for your classes so that your question makes sense for other languages.
There are languages where operators can be overridden, such as C ++ and Python. If you are interested in such a comparison, why not give it a try? Even from your tests shows that the "+" operator is slower / faster than the .add () method, which can change when the compiler or environment changes.
I think you should use something that's good for you.
Java has recommended using StringBuffer
the +
c instead of the operator String
, but the latest Java implementations improve optimizations for the operator +
, so this advice is not appropriate for new code.
a source to share