Note that there are some explanatory texts on larger screens.

plurals
  1. POJava, Memory usage for "Scanner"
    text
    copied!<p>I'm running an online automatic program evaluation platform and for one of the exercises the Java "Scanner" is using way too much memory (we are just starting to support Java so the problem did not arise before). As we are teaching algorithmics to beginners we can't just ask them to re-code it themselves by reading one byte after an other.</p> <p>According to our tests, the Scanner is using up to 200 Bytes to read ONE integer...</p> <p>The exercise : 10 000 integers, which window of 100 consecutive integers has the maximal sum ?</p> <p>The memory usage is small (you only need to memorize the last 100 integers) but between a classical version with "Scanner / nextInt()" and the manual version (see below) we can see a difference of 2.5 Mb in memory.</p> <p>2.5 Mb to read 10 000 integers ==> 200 Bytes to read one integer ??</p> <p>Is there any easy solution that one could explain to a beginner or is the following function (or similar) the way to go ?</p> <p><hr> Our test-function to read integers much faster while using much less memory :</p> <pre><code>public static int read_int() throws IOException { int number = 0; int signe = 1; int byteRead = System.in.read(); while (byteRead != '-' &amp;&amp; ((byteRead &lt; '0') || ('9' &lt; byteRead))) byteRead = System.in.read(); if (byteRead == '-') { signe = -1; byteRead = System.in.read(); } while (('0' &lt;= byteRead) &amp;&amp; (byteRead &lt;= '9')) { number *= 10; number += byteRead - '0'; byteRead = System.in.read(); } return signe*number; } </code></pre> <p><hr> Code using Scanner, as requested : </p> <pre><code>import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int nbValues = sc.nextInt(); int widthWindow = sc.nextInt(); int values[] = new int[widthWindow]; int sumValues = 0; for (int idValue = 0; idValue &lt; widthWindow; idValue++) { values[idValue] = sc.nextInt(); sumValues += values[idValue]; } int maximum = sumValues; for (int idValue = widthWindow; idValue &lt; nbValues; idValue++) { sumValues -= values[ idValue % widthWindow ]; values[ idValue % widthWindow ] = sc.nextInt(); sumValues += values[ idValue % widthWindow ]; if (maximum &lt; sumValues) maximum = sumValues; } System.out.println(maximum); } } </code></pre> <p>As requested, memory used as a fonction of the number of integers : </p> <ul> <li>10,000 : 2.5Mb</li> <li>20,000 : 5Mb</li> <li>50,000 : 15Mb</li> <li>100,000 : 30Mb</li> <li>200,000 : 50Mb</li> <li>300,000 : 75Mb</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload