God gives us strength by virtue of His faithful love to us. David was willing to cling to it even as he was being hunted down as an enemy of the state by King Saul whom he had faithfully served. The events that led to David's song here are recorded specifically in 1 Samuel 19:11. David was being pursued by Saul's agents. He had to escape through a house window. It was a time of distress for David.
I am sure that he did not like that Saul had made him public enemy number one. And all that David did at that time and up to that time made it perfectly clear that he did not deserve the designation. Jealousy drove Saul to hunt David down in murderous rage. But trust is what motivated David, even while on the run from Saul. His faith led him to trust God for the outcome and the protection that he needed.
David fully knew God's unfailing love. And that knowledge led him to worship God, even as he ran for his life from Saul's forces. The capacity for God's protection far exceeded the fear of David's own death. And in that refuge of God's protection David found strength. God's faithfulness and strength are much bigger than our fears.