简体   繁体   中英

Catching an exception instead of comparing array values for performance?

I have a function that generates a path from one position in a 3x3 matrix to another so I can animate an image transition on a direction change smoothly. It returns an array containing positioning parameters that are translated in CSS classes, eg: ["top left vert", "left slow", "left"] . The transitioning is handled in subsequent setTimout() calls in my animation logic.

At the end of a move cycle, the element in question returns to a stop position. This transition isn't handled by the function that generates the path, instead it throws an exception. In my animation logic I have a try/catch block where I simply ignore the exception if it's thrown. This way I know that I have to execute my stop transition:

var move = moveClass.join(" ");
try {
    move = updateDirection(move);
} catch(e) {}

if (move instanceof Array) {…} else {/* stop */}

Instead of throwing the exception the function could return the same position in the array, where I would have to compare the elements of the array (instead of using instanceof Array ).

I know that one shouldn't abuse exceptions like this. ;-) My question is: Is this more expensive than checking the contents of the array (eg if (move[0] == move[1] && move[0] == move[2]) )?

Performance results will vary depending on the environment it is running in. So different browsers, OS, etc could all have an impact.

Having said that generally throwing exceptions is quite an expensive thing to do (just think of all the work involved in building stack traces, generating objects, etc). So in most cases you are better off using a comparison if you can.

As a general design principle in most if not all languages Exceptions should be just that - exceptions to the norm. You should not be using them to control the usual flow of your program, but instead to handle rare outlying or exceptional cases, usually involving errors, failures, or mistakes of some sort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM