Why might Shakespeare have created characters like this-Are they there for comic relief-do they serve a more serious purpose?

Consider Rosencrantz and Guildenstern’s role in the play. Why might Shakespeare have created characters like this? Are they there for comic relief, or do they serve a more serious purpose? Why does the news of their deaths come only after the deaths of the royal family in Act V, as if this news were not anticlimactic? Is it acceptable for Hamlet to treat them as he does? Why or why not?