Is Calling `crypto.Hash.destroy` Required?

I have a simple function that, given a string, returns the SHA-256 hash of that string as a hexadecimal string.

function computeSHA256Hash(string) {
    const hash = crypto.createHash('sha256');
    hash.update(string);
    return hash.digest('hex');
}

There is a method named destroy on the crypto.Hash object returned by crypto.createHash. Do I need to call it?

function computeSHA256Hash(string) {
    let hash;
    try {
        hash = crypto.createHash('sha256');
        hash.update(string);
        return hash.digest('hex');
    } finally {
        if (hash) {
            hash.destroy();
        }
    }
}

>Solution :

As that function doesn’t appear in any of the documentation, including examples, it is likely an internal thing that can be left alone.

If you’re concerned about memory leaks, that’s rarely a problem in JavaScript, and any such cases where you do need to pay attention are often highlighted in the documentation as these are unexpected. The Garbage Collector does a good job of cleaning up things once you’re done with them.

There are occasions where you might want to release resources early, which some libraries do make accommodations for, but this is more of a convenience than a requirement, provided for those situations where memory is extremely tight and must be conserved.

Leave a Reply