My question specifically is for Perl but I would like to be enlightened for most languages.
Is there an actual difference (performance-wise and efficiency-wise) between using an eval() function, versus an if() statement?
eval(-e /path/to/file) or die "file doesn't exist";
if (! -e /path/to/file) { die "file doesn't exist"; }
First of all, don’t micro-optimize like this. It is far more important to write code that you can most easily follow the sense of. Keeping this in mind will result in fewer bugs, and avoiding one bug is more important than saving a great number of nanoseconds.
That said, you can examine how perl compiles things like so:
You can see some trivial extra operations involved in the second for the logical not of the result of -e, entering and leaving the
{}block, and for having the die as a separate statement. That separate statement can be useful; if you are stepping through the code in the debugger, it stops before dieing.Using Perl 5.12+ or using
unlessinstead ofif !in older version of Perl removes thenot:Using a statement modifier produces the same results as the
-e ... or diecode: