Efficiency Source.fromFile

I wonder what the effectiveness of the following fragment is:

val lst = Source.fromFile(f).getLines.toList 

When lst.contains(x) ,

Does this mean that f rescanned, or is it that the search relies on the contents in memory f in the newly created list?

Thanks in advance.

+4
source share
2 answers

Search is based on content in memory. And it loads only after calling toList .

What is the best way to see directly from source . Source.fromFile returns a scala.io.BufferedSource . getLines returns a BufferedLineIterator .

Here in BufferedLineIterator the contents of the files are read.

 override def hasNext = { if (nextLine == null) nextLine = lineReader.readLine nextLine != null } override def next(): String = { val result = { if (nextLine == null) lineReader.readLine else try nextLine finally nextLine = null } if (result == null) Iterator.empty.next else result } } 

To call the toList list toList use next and hasNext above. So lst already contains all the elements of the file.

Running lst.contains(x) through the list like any other list.

+4
source

Once you use toList, it will return you an immutable list to work with. your file will not be scanned for operations that you do in the list that you received.

+2
source

Source: https://habr.com/ru/post/1494198/


All Articles