Skip to content

Stack overflow in LinkedListLike.size #4165

@scabug

Description

@scabug

It is quite bad implementation in "size" method of scala's LinkedList.

trait LinkedListLike … { self =>
  
  override def length: Int = if (isEmpty) 0 else next.length + 1

This way leads us to linear stack growing while algorithm iterates over collections. Every call of "next" goes to stack and after thousands or hundreds elements we have StackOverFlow error.

And time consumption is too large even with small number of elements.

It would be better to realize "length" and "size" methods without recursion (now it's not tail-recursion!). Something straitforward like Java's one:

trait LinkedListLike … { self =>
  
  override def length: Int = {
    //Pseudocode!!!
    if (isEmpty) 0 {
      var iter = this.iterator
      var counter = 1
      while(!iter.next.isEmpty) {
        counter += 1
      }
      counter
    }
  }

It's not so compact as now but it will work 10 000 times faster and without StackOverflow.

=== What versions of the following are you using? ===

  • Scala: 2.8.1

Activity

scabug

scabug commented on Jan 17, 2011

@scabug
Author

Imported From: https://issues.scala-lang.org/browse/SI-4165?orig=1
Reporter: Lex (lex-kravetski)

scabug

scabug commented on Jan 17, 2011

@scabug
Author

@paulp said:
Duplicate of #3996, and look at up to date sources before opening tickets.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @scabug

        Issue actions

          Stack overflow in LinkedListLike.size · Issue #4165 · scala/bug