Skip to content

Proposal: fast path for assert.deepEqual with typed arrays #4294

Description

@LinusU

assert.deepEqual is very slow when given large typed arrays. This is however easily worked around by wrapping them in buffers instead. It would be awesome if Node.js could use the same performant code to compare Typed Arrays as it uses for buffers.

This is my current local workaround:

function assertTypedArrayEquals (actual, expected, message) {
  const actualBuffer = new Buffer(actual)
  const expectedBuffer = new Buffer(expected)

  if (actualBuffer.equals(expectedBuffer)) return

  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: 'deepEqual',
    stackStartFunction: assertTypedArrayEquals
  })
}

This brings the test down to a few milliseconds from over one second.

Activity

  1. added
    assertIssues and PRs related to the assert subsystem.
    on Dec 15, 2015
  2. added
    good first issueIssues that are suitable for first-time contributors.
    and removed
    good first issueIssues that are suitable for first-time contributors.
    on Dec 16, 2015
  3. silverwind commented on Dec 16, 2015

    @silverwind
    Contributor

    @LinusU can you quantify how much faster this is? Also, it might be interesting how such an optimization will affect other type's assertions.

  4. LinusU commented on Dec 16, 2015

    @LinusU
    ContributorAuthor

    Test case:

    var assert = require('assert')
    
    var a = new Uint8Array(1e6)
    var b = new Uint8Array(1e6)
    
    console.time('typed array')
    assert.deepEqual(a, b)
    console.timeEnd('typed array')
    
    console.time('buffer')
    assert.deepEqual(new Buffer(a), new Buffer(b))
    console.timeEnd('buffer')

    Result:

    typed array: 3216.043ms
    buffer: 16.126ms
    

    About 200 times faster for an array of 1,000,000 bytes.

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

    assertIssues and PRs related to the assert subsystem.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions