0
<script>
  var num=10;

  while(num<=20000000){
    document.write(num+'<br/>');
    num++;
  }
</script>

As you can see above num starts at 10 and goes till 20 million. But, this program does not work on my computer. My computer just freezes after running this code for few seconds. Does 20 million is very big value which javascript can't handle or their is issue with browser memory about which I am unaware. If I run same logic in c , it does work. What's the problem here?

My computer configuration : 

Main Memory : 2GB

processor : Intel Quad core processor ( up to 2.66 GHz)
James Z
  • 12,209
  • 10
  • 24
  • 44
WeAreRight
  • 885
  • 9
  • 24
  • Viewer cannot read twenty million lines in `document` at once. Using `while` loop is not necessary. Append `#text` nodes to `document` incrementally. – guest271314 Feb 18 '17 at 06:55
  • Modifying the DOM is expensive. You can have better luck concatening the string and adding it at once (or each million, perhaps). – mrlew Feb 18 '17 at 07:00
  • See [jQuery - Can threads/asynchronous be done?](http://stackoverflow.com/questions/26068821/jquery-can-threads-asynchronous-be-done/) process 10,000 items 250 items at a time; [How to solve Uncaught RangeError when download large size json](http://stackoverflow.com/questions/39959467/how-to-solve-uncaught-rangeerror-when-download-large-size-json/) process download of 189.8 MB (189,778,220 bytes) file – guest271314 Feb 18 '17 at 07:16

1 Answers1

2

The real bottleneck here would the browser rendering. Don't forget that you are adding a huge amount of data to the DOM that all has to be handled.

If you just want to try out loops and play around in Javascript, maybe the better choice would be to use NodeJS where you can run your program outside of the browser environment

var timerLabel = 'running_loop';
function loop() {
  var num = 5;
  while (++num < 20000000) {
  }
}

// starts a timer
console.time(timerLabel);
loop();
// marks in ms how long the operation took
console.timeEnd(timerLabel);
Icepickle
  • 12,689
  • 3
  • 34
  • 48