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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.