Is this actually something you could compute in a formula using
according some variables as assumptions?
This is an age old question, and isn't new.
If you get a 30 year mortgage, and keep that mortgage until the loan is paid off, then due to the nature of the declining loan amount less and less of the payment is interest. Also over those decades as your income grows, and the kids move out of the house, the loan becomes easier to pay for. That leads to the dilemma: should I pay it off faster, or use the extra cash I have each month to invest in my retirement funds, or travel, or get a new expensive car?
There is a related question that sparks debate: do you want to still want to have a mortgage in retirement, or is the goal to payoff the mortgage before you retire?
These issue spark articles, blog posts, chapters of books, even whole movements and books.
Determining what to do is a personal decision. The formulas and spreadsheets can help put some of this into focus. But they can't answer it fully due to uncertainty: how will the market act over the next X years? You also have to make assumptions regarding future income, and future expenses.
The biggest issue is that it can't measure your personal goals, or what will make it easier to sleep at night. Some people need to pay the mortgage off as quickly as possible. Others have no problem keeping it well past retirement.
Investing that extra cash does have risks. But if you are behind on your retirement savings then putting the extra money into your retirement accounts could make sense. Paying extra on the mortgage locks that extra cash away, but if next year you lose your job it didn't lower your monthly expenses unless your refinance. Of course getting money out of your retirement accounts isn't easy either.