If I have to use a param from the event in a loop, is it better to extract the params to a variable before (e.g. const params = event.getParams()), and use that variable instead of calling event.getParams() in the loop?

Or is that call to getParams() not really expensive and it practically does not really matter?

Here's an example to make it more clear:

function handleEvent(event) {
    // const params = event.getParams();    

    array.forEach(function(element) {
        if(element.type === event.getParams().type) { // use `params` instead `event.getParams()`?
            // do something

Given that readability is about equal, you might as well cache beforehand. It certainly will perform better, even if it only saves nanoseconds. Especially if you have end users who have poorer hardware or connections, every optimization counts.


Don't worry about which one you use in regards to performance. They have similar characteristics in terms of performance. The only real difference is that you can make code more legible with getParams:

 const params = event.getParams();
 if(params.someValue) {
    // etc...

I would advise against the getParams().x form, as that's simply an odd way of writing the code, especially if you're reading multiple parameters.

One other thing to note, though, is that if the parameters are dynamic, using getParams() allows you to use Object.keys() to determine which parameters are present.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.