Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

simpler api vs penalty ? #7

Closed
gabssnake opened this issue Oct 21, 2021 · 2 comments
Closed

simpler api vs penalty ? #7

gabssnake opened this issue Oct 21, 2021 · 2 comments

Comments

@gabssnake
Copy link

Hi, thanks for this and the related article!
Was wondering why you picked a two-step API instead of a single step?
Is there any significant penalty?

Usage:

const partitionWhenStarved = EventLoopSpinner()
for (const item of items) {
  expensiveCalculation()
  await partitionWhenStarved()
}

For example:

function EventLoopSpinner(threshold = 10) {
  let last = Date.now()
  return async () => {
    if (Date.now() - last < threshold) return
    return new Promise(resolve => setImmediate(() => {
      last = Date.now()
      resolve()
    })
  };
}
@FauxFaux
Copy link
Contributor

It's amazingly slower, as you always hit an await. On my machine (linux, node 14), it's 32x slower in a tight loop.

const bench = require('nanobench');
const ES = require('event-loop-spinner/dist/event-loop-spinner').EventLoopSpinner;

bench('spin recommended', async function (b) {
  b.start()

  const spinner = new ES(9000);
  for (let i = 0; i < 2_000_000; i++) {
    if (spinner.isStarving()) {
      await spinner.spin();
    }
  }

  b.end()
})

bench('spin function', async function (b) {
  b.start()

  const spinner = new ES(9000);
  for (let i = 0; i < 2_000_000; i++) {
    await gabssnake(spinner);
  }

  b.end()
})

async function gabssnake(spinner) {
  if (spinner.isStarving()) return;
  await spinner.spin();
}
NANOBENCH version 2
> /usr/bin/node spinner.js

# spin recommended
ok ~91 ms (0 s + 91346194 ns)

# spin function
ok ~2.92 s (2 s + 918358811 ns)

all benchmarks completed
ok ~3.01 s (3 s + 9705005 ns)

@gabssnake
Copy link
Author

Wow, thanks for the great info. Cheers,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants