Why does this take so long to run?

io, java

Solution

You are concatenating to text every iteration, and Strings are immutable in Java. This means it creates a new `String` object in memory every time `text` is "modified," resulting in long load times for large files. You should always try and use a `StringBuilder` when you are continuously altering a `String`.

You could do:

StringBuilder text = new StringBuilder();
Scanner sc = new Scanner(new File("text.txt");
while(sc.hasNext()) {
  text.append(sc.next());
}

When you want to access the contents of text, you can call `text.toString()`.

Problem

I'm a newbie to java, and I'm reading in a ~25 MB file, and it takes forever to just load... Are there any alternatives to make this faster? Is it the Scanner that can't handle large files? ``` String text = ""; Scanner sc = new Scanner(new File("text.txt")); while(sc.hasNext()) { text += sc.next(); } ```

Original source