Java: faster overloading or if / else

I have children's classes, and each class has other members who bring different types of value There may be longobject, intobject, stringobject, etc

I will get a value, which can be long, int, string, etc. I must create a longobject, stringobject, etc. respectively

Is it faster (a) to overload the method as shown below, or only use else if (b) as shown below?

It may not be a significant performance difference It is possible that overloaded methods are implemented in a manner similar to if / else I don't know.

I can also hear some of you say you want to test Of course, I should If anyone knows, I also want to know how to handle this type of overload under the hood

Please let me know what you're thinking

Thank you, JBU

(one)

BaSEObject getObject(long l)
{
     return new LongObject(l);
}

BaSEObject getObject(int i)
{
     return new IntObject(i);
}

BaSEObject getObject(String s)
{
     return new StringObject(s);
}

...

b)

BaSEObject getObject(Object x)
{
    if(value is a long)
         return new LongObject((Long)x);
    else if(value is an int)
         return new IntObject((Int)x);
    else if(value is a String)
         return new StringObject((String)x);
    ...
}

Editor: I think I didn't add all the details completely. Some people caught it For both options, I still need to get an object / value and determine what type it is from the value Therefore, I still need to use if / else or even some overloaded method

Solution

There is a big difference: overload is selected at compile time, and your "if (long value)" will be run-time test

If you know the type at compile time, I strongly recommend that you use this information If you don't, the overload option is not feasible anyway

Editor: comments suggest that I specify the overload selected at compile time

The compiler selects which method signature to call based on the compile - time information about the parameters This is different from the coverage method, in which the method implementation used is determined by the type of actual goal of the method

Here is an example:

public class Test
{
    public static void main(String[] args)
    {
        Object x = "I'm a string";
        foo(x);
    }

    public static void foo(String x)
    {
        System.out.println("foo(String)");
    }

    public static void foo(Object x)
    {
        System.out.println("foo(Object)");
    }
}

This prints foo (object) because the compile time type of X is object, not string The execution time type of the object referenced by X is string, which does not mean that foo (string) is called

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>