0

Which one is a better approach 1st or 2nd in terms of performance ?

const getCookieValue = readCookie('my_var') should be declared at top or since its usage is only in a condition so better to keep it inside if statement

Approach 1

componentWillMount() {
  const {data1, data2} = this.props
  if(data1) {
    const getCookieValue = readCookie('my_var')
    if(getCookieValue === 'test_string') {
      // Statements ....
    }
  }
}

OR

Approach 2

componentWillMount() {
  const {data1, data2} = this.props
  const getCookieValue = readCookie('my_var')
  if(data1) {
    if(getCookieValue === 'test_string') {
      // Statements ....
    }
  }

}

Nesh
  • 2,389
  • 7
  • 33
  • 54
  • 2
    Performance wise it is faster to only do the operation if it is on the logical path where that variable is needed. But it is going to be almost negligible in this case – Benjamin Charais Sep 13 '18 at 18:24

1 Answers1

1

performance wise - Approach 1, you answered your question - since its usage is only in a condition so better to keep it inside

givehug
  • 1,863
  • 1
  • 14
  • 19