Is a good practice defining variable outside class scope in angualr?

  • A+
Category:Languages

It is common to see these code in Angualr:

import { Component, OnInit } from '@angular/core';  @Component({     selector: 'app',     template: '<div *ngFor="let item of data"></div>' }) export class App {     // we define variable here     data = [1, 2];     tempData = [3, 4]; //temporary data, not involved in view rendering } 

As we can see, there is a temporary variable won't involve in view rendering, but the temp variable is also necessary for our application in the use of storing data temporarily.

what about writing like this:

import { Component, OnInit } from '@angular/core'; const tempData = [3, 4]; //temporary data, not involved in view rendering     @Component({         selector: 'app',         template: '<div *ngFor="let item of data"></div>'     })     export class App {         // we define variable here         data = [1, 2];     } 

Since the temporary variable won't be used in view rendering, I can define it outside of the class. And in my opinion, it will optimize the performance(because it reduce the detection variable for angular, I dont't know whether it is right).

So which code style is better, and it has performance difference between them ?

 


In your first example, there's a tempData for each instance of your class (it's not a variable, it's a property). In your second example, one tempData is reused by all instances of your class (and in this case, it isn't a property, it's a constant).

Which you use depends on whether you need a per-instance tempData or a shared one.

Declaring it at the top-level of your module if it's private information and you don't need it to be per-instance is absolutely fine. It will be private to that module.

So which code style is better, and it has performance difference between them ?

Neither is better; they're different, and do different things, so you use one or the other based on what you need to do. Any performance difference between them will be utterly and completely negligible, nothing to bother thinking about.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: