What's optimal duration of car loan?

Dear all,

I am looking to purchase a new car to retire my 2006 Honda Civic.

I am looking at a 40K Mazda with $5k down payment and following options

  • 3 yr loan @ 3.9% coming to around $1k per month mortgage payment

  • 6 yr loan @ 5.9% coming to $580 per month payment

  • both are through Mazda. I will look into other financing through credit unions closer to the purchase date in upcoming months

I am trying to understand what would be the right balance between paying off the loan by the time point where the depreciated car stops being worth less than the money I owe to the bank VS having that money going to my investment account.

If I am interpreting things correctly, I will pay $5k more in interest.

However, if I put the monthly mortgage difference of $455 into an index fund, I will make $40k at the end of those 6 years.

So the 6 year mortgage looks like a no brainer.

Am I missing something?

I feel comfortable about having this new debt. Only debt I owe is house mortgage. I psy all credit cards in full each month.

Any advise or insight would be greatly appreciated.

Thank you all

Edit #2. Decision made. Will got for the shortest duration probably 3 years.