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

Decimal.sum with large arrays exceeds the maximum call stack size #230

Open
mgkalogirou opened this issue Nov 16, 2023 · 4 comments
Open

Comments

@mgkalogirou
Copy link

Problem

The current implementation of the Decimal.sum function requires spreading the array contents, which may lead to exceeding the maximum call stack size for large arrays. This results in a breaking point, and the function fails for arrays around 70k elements.

Expected Behaviour

The Decimal.sum function should be modified to accept an array directly, rather than relying on spreading the array contents so that large arrays can be summed.

Steps to Reproduce

Create a large array, for example:

const bigArray: number[] = Array.from({ length: 100e3 }).fill(1) as number[];

Attempt to use Decimal.sum with the large array:

const decimalSum = Decimal.sum(...bigArray);

Environment

decimal.js: ^10.4.3
Node.js version: v18.17.1
TypeScript version: 5.2.2

@nilaygit-10721
Copy link

can you assign this issue?

@nilaygit-10721
Copy link

/attempt

@josdejong
Copy link

josdejong commented Oct 13, 2024

You can easily write your own version of sum, like:

function sum(array) {
  return array.reduce((total, value) => total.add(value))
}

@heikomat
Copy link

heikomat commented Nov 4, 2024

Beware that when you call Decimal.sum(...bigArray), you're effectively calling sum with 100'000'000 arguments.

The issue you're seeing could very well be a limit of how many arguments you can pass to a function, instead of being an issue with this library.

According to this StackOverflow-Answer (from 2014) and this blog-post (from 2021), the limit for V8 and JavaScriptCore seems to be at about 65k arguments. More than that, and those engines will throw a "Maximum call stack size exceeded" error

Update: Sorry for not reading your initial issue fully before posting. It seems you're aware of what is actually the problem

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

4 participants