Sometimes it’s required to add custom code which extends the functionality of your website. In WordPress you have two ways which are recommended.

Theme’s functions.php

A file called functions.php should be placed in the root of your themes folder at wp-content/themes/yourtheme/functions.php. If this file doesn’t exists create a new one and place all your custom code in this file.

Your custom code will only get executed if this theme is active. If you switch to a different theme all the code in your functions.php file will stay unused.

Dedicate Plugin

If you like to use custom code across multiple themes you should create a dedicate plugin. While creating a plugin for WordPress is a bit more complex it will bring the advantage of disabled it explicitly via your backend.

Please check the official guide on how to create a plugin.

There no difference in performance if you put your code in the functions.php or in a plugin.

Please find more info about customization in the WordPress environment on the official website.