1

In recurring functions such as CustomPaint()'s paint(), if I create an object this way:


void paint(Canvas canvas, Size size) {
    
  ....
  
  var myObj = MyClass();
  var myObj.configure(canvas, size);
 
  ....
    
}

Will this object get recreated while paint() gets called every frame or will it be cached until something it depends on such as screen size changes?

kakyo
  • 10,460
  • 14
  • 76
  • 140

1 Answers1

3

It depends on how you implement MyClass constructor. I can see several options:

  • MyClass standard constructor - then object will be recreated every time it is called;
  • MyClass can have const constructor. Then if you create instance with const MyClass() it will be same instance. Therefore it is not always possible to do that.
  • MyClass can have default factory constructor. This way you can implement "caching" inside MyClass itself depending on your requirements. Example is "singleton" - you will always have single instance. See here for example: How do you build a Singleton in Dart?

Please note also that if objects of MyClass are lightweight it could be that you do not need to optimize: Dart is usually good creating lots of small objects and garbage collecting them.

Alex Radzishevsky
  • 3,416
  • 2
  • 14
  • 25