flutterdart

Dart + Flutter new object creation


In dart I can create an object and call a method in two ways:

First one:

ClassA a = ClassA();
a.methodA();

Second one:

classA().methodA();

Does it have any negative effect to keep doing this? Let's say I want to call 4-5 methods from ClassA in another class, would it have any negative effects, f.x. on performance by using the second way?


Solution

  • That's still the exact same object creation process, it's just a simple constructor call. The only difference is that in one case you're giving the result a name (a), in the other you're not.

    It's not like you're saving memory by not saving the object to a variable. In either case, a reference to your new ClassA object needs to exist somewhere, (whether explicitly named or not), otherwise how would methodA know which object to operate on?

    However, there is a difference between:

    ClassA a = new ClassA()
    a.methodA()
    a.methodB()
    a.methodC()
    a.methodD()
    a.methodE()
    

    versus

    new ClassA().methodA()
    new ClassA().methodB()
    new ClassA().methodC()
    new ClassA().methodD()
    new ClassA().methodE()
    

    In the first case, you're reusing the same object a (from a single constructor call) as a target of all 5 instance method calls. In the latter case, you have 5 distinct objects (from 5 separate constructor calls), each as a target of a single method call. These can obviously have very different semantics.