Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

flutter - Dart: Is there a disadvantage to using const constructor?

There is an analyzer/lint check to warn me when it is possible to use a const constructor: https://dart-lang.github.io/linter/lints/prefer_const_constructors.html

(ie. using final a = const A(); instead of final a = A();)

I think to understand the advantages (there will only ever be one instance with the same constant values for a const constructor). But why isn't this the default? Since dart 2 the new can be omitted, so why didn't they change the definition of creating a new instance which can be created const simply as const instead of new? I assume there must be some disadvantage to having everything const?

(for example in a constant context like const [A()] it is actually the same as const [const A()], so why not everywhere)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

so why didn't they change the definition of creating a new instance which can be created const simply as const instead of new?

If you mean why doesn't final a = A(); automatically assume const A() if A has a const constructor:

  1. Sometimes it is automatic:

    const a = A();
    

    in which case A's constructor is being invoked in a const context and doesn't need an extra const qualifier on the right-hand-side.

  2. An explicit const expresses intent. For example, suppose you had:

    final a = A(B());
    

    where A and B have const constructors. Later, somebody makes a change:

    final a = A(C());
    

    where C does not have a const constructor. If const were automatic, then you would have no idea that a is no longer const. Maybe that's okay, but it also could suddenly have a negative impact on your application's performance, and without an explicit const qualifier, the impact of a local change could have a much wider scope than expected. (That said, explicit const qualifiers and automatically adding them aren't mutually exclusive.)

  3. const can have downsides. const creates compile-time constants. If you have:

    final a1 = A();
    final a2 = A();
    

    identical(a1, a2) is not true. If const A() were implicit, then identical(a1, a2) would be true, and maybe that's not a property that the code intended to have.

  4. I think that compile-time constants live forever. The whole point is to have an object that can be reused instead of re-constructing it. The flipside is that they can't really be destroyed easily.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...