Skip to content

Times when you may need loops (re: performance) #8

@richardeschloss

Description

@richardeschloss

Hi, I just submitted a pull request #7 that shows a significant performance improvement with some simple code changes. However, even with this performance improvement, the for loop still performs much better, or at least in my environment. My environment: Chromium 73 (linux).

Consider the following test:

const unfold = (f, seed) => {
  const next = (f, val, acc) => {
    if (!f(val)) return acc
    const [currVal, nextVal] = f(val);
    acc.push(currVal)
    return next(f, nextVal, acc); 
  }
  return next(f, seed, [])
}

const rangeCorecursion = (start, end) =>
  unfold(val => (val <= end) 
    ? [val, val + 1]
    : null
, start);

const rangeLoop = (start, end) => {
  const acc = []
  for (let i = start; i <= end; i++) {
    acc.push(i)
  }
  return acc
}

const end = 5000
console.time('range_(corecursion)')
const range_test1 = rangeCorecursion(0, end)
console.timeEnd('range_(corecursion)')

console.time('range_(loop)')
const range_test2 = rangeLoop(0, end)
console.timeEnd('range_(loop)')
// Results:
range_(corecursion): 31.378173828125ms
range_(loop): 2.19482421875ms

As soon as I bump up the "end" to anything over 5000, chromium encounters "max call size errors". Using the for loop, not only do I not encounter that error, I can bump up the end range all the way to about 135,000 and have it finish before the corecursion method finishes 5000 iterations.

Is the performance different on Safari? What do those numbers look like?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions