12

window.onresize = window.onload = function(){
  if(window.innerWidth < 480){
    document.getElementById('alert').onclick = function(){
      alert('<480');
    };
    //large amounts of code
  }
  if(window.innerWidth >= 480){
    document.getElementById('alert').onclick = function(){
      alert('>=480');
    };
    //large amounts of code
  }
}
<button id="alert">Alert</button>

In the above code if window.innerWidth is greater than 480, will the code inside first if be processed by the Javascript engine? The second block will be executed and I will have the function in memory and assigned to #alert.onclick. The question is will the function inside the other(false) condition be there in memory as a variable may be like a dangling reference or will that function be bootstrapped only when the condition is true?

This is to understand if there is any advantage in terms of initial amount of code processed when window loads if the code for mobile is inside conditional statements like this and is considerably large..

I'll be glad to see any documentation on how a function is bootstrapped and stacks allocated and when.

8
  • Interestingly, I read an article about this just yesterday... Let me see if I can find it again. But from what I remember, yes - the processor will process everything, not respecting any conditional statements. (that's also why you can call functions before they are even declared - keyword "hoisting") Hope I can find the link again to confirm this assumption... Commented Feb 16, 2017 at 12:45
  • 3
    @Connum: function expressions (document.getElementById('alert').onclick = function () { ... } ) are not hoisted. See: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Feb 16, 2017 at 12:48
  • Thanks for the reminder! Commented Feb 16, 2017 at 12:52
  • @Connum: no worries. Don't get confused between function declarations, which are hoisted. See: developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Feb 16, 2017 at 12:56
  • 2
    Don't the runtimes look-ahead at everything with an eye to optimize (number of times function is called, globals, etc), and/or if it needs a "bailout"? I would think if a runtime left out any kind of processing and only bootstrapped a function when the path was executed, performance could suffer greatly and tons of opportunities for optimization could be overlooked. For example, by the same logic, the internal of a handler wouldn't be processed unless the event kicked over, but I don't think it works that way. Also, I think what exactly occurs can be engine-specific. Commented May 7, 2017 at 19:35

4 Answers 4

5
+25

Yes all the code will be parsed

And No, not all the code will be processed/executed.

What you are doing is a conditional assignment. on load and on resize

Means that if condition is true/false on function call load/resize the onclick property will be set/overwritten accordingly.

There is a difference between assignment and declaration

assignment:

assigned = function(){ console.log("blabla") }

declaration:

function declared(){ console.log("blablabla")}

function declarations will be hoisted (what you describe by "parsed and stored into memory before actual execution"), so:

You ask about performance so your actual question is depending on what you describe is "large amounts of code". if you are not talking about like 1mb of js-code in between there with tons of function declarations... dont worry.

and just as a note, never try to debug your js with alert() because it will stop all execution unless you interact with the popup. Means that if your alert fires when width > 479 and for some reason your width gets smaller than 480 in the meantime (for example orientation change on a device), your assignment wont happen!!!

as i pointed out in the comment below, you can test the parse and execution performance like this:

<script>
  var startTime = new Date().getTime();
</script>

// your stuff 

<script>
  console.log(new Date().getTime() - startTime)
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

The alerts are from the original code I saw in another question, I understand how alert works and also hoisting. My doubt is how JS engines handles functions and other code inside conditions. So will it make a difference if the code is loaded asynchronously for each condition.
afaik and as i pointed out, all of the js-engines will parse all your code but it will only be conditionaly executed. One difference will definetly be that you will have another server request with its respond time lets assume it is between "100-600ms", check out this link how fast different devices parse jquery (1-100ms) timkadlec.com/2014/09/js-parse-and-execution-time
1

JS engines performance differs for both sync and async call. If it is ansync, yes it will be faster and called only if any conditions are satisfied else it is ignored but the code should have the logic/conditions so that there wouldn,t be any run time js error occurrences happening. example - bottleneck or simultaeously firing two async calls where response are inter dependent.

InShort- synchronous code is executed in sequence – each statement waits for the previous statement to finish before executing. Asynchronous code doesn’t have to wait – your program can continue to run.

It completely depends on the requirements/solutions. If there are many async call used in your JS use -https://github.com/caolan/async

Comments

1

All the code is definitely parsed by the engine, say if you have any compilation errors in the block which it may not execute, it still throws error.But it will execute any code inside that block, so if have any local variables or functions defined there you may not be able to use them in other parts and yes it will not be in memory because that will never be executed.

So even if you have lots of code or any infinite loop in the block which is not executed(like your first if block there wont be any difference in performance.Only problem is if you are serving it from a web page on a network then due to the file size(if its so large) you may get a difference. You can check this by debugging your code from chrome dev tools or firebug.Just put a debug point in the first code block and second then you can observe it.

Comments

1

You asked;

This is to understand if there is any advantage in terms of initial amount of code processed when window loads if the code for mobile is inside conditional statements like this and is considerably large..

I would add an infinite loop and run it to see if there is an effect, like this:

window.onresize = window.onload = function(){
  if(window.innerWidth < 480){
    while(true){
        console.log("abc");
    }
    //large amounts of code
  }
  if(window.innerWidth >= 480){
    document.getElementById('alert').onclick = function(){
      alert('>=480');
    };
    //large amounts of code
  }
}

2 Comments

I am interested in how an optimisation compiler handles such cases rather than execution. It is obvious that code inside false conditional statement won't be executed.
As i cited from your post above, your point was about performance, so i approached this problem like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.