1

Does the size of an array object element affect the performance of sorting the array?

I suspect the answer is no, because only memory pointers (if I get it correctly) are sorted. But I would be grateful if someone who knows will confirm/reject/explain this.

The property by which to sort contains a number: 1,2,3 etc..

Example of the two arrays:

const arr1 = [{blob: {/*huge object here*/}, order: 1}, /*similar objects*/]

const arr2 = [{smallObject: {foo: 'bar'}, order: 1}, /*similar objects*/]

// sorting like this:
arr.sort((a,b)=> a.order > b.order ? 1 : -1)
4
  • No it dosen't depend on the size of individual element. it depends on the number of elements in array. Commented Mar 10, 2019 at 10:06
  • How do you sort them? Commented Mar 10, 2019 at 10:08
  • @gilamran I've added the sorting code Commented Mar 10, 2019 at 10:09
  • The compare time will be affected by the average number of reads it takes to do a compare. For example, if the objects are strings that are nearly identical, then an array of larger strings will take longer to sort than the array of smaller strings due to the compare time. Commented Mar 10, 2019 at 17:27

2 Answers 2

3

No. Pointers are the only way to represent dynamic nested structures efficiently, so the "size" of objects won't affect the sorting, as just pointers have to get swapped.

The size of the array however does affect the sorting speed, if there are more elements you have to sort more.

Sign up to request clarification or add additional context in comments.

Comments

1

I've created a benchmark here: http://jsben.ch/vSVZa

enter image description here

4 Comments

Cool! So the size of an object does affect the performance of sorting (though slightly). UPD, no it doesn't really :-) First time the array with lighter objects was 5% faster, second time it is 1% slower, then it is 6% slower, then faster again etc. Thanks for making the benchmark! I was too lazy to make it (an apologize for that).
Browser specific though. Also if you run jsben.ch/vSVZa for 10times, you might get block 1, fastest one or two times.
Any execution will differ as you are testing it on a "busy" computer... generally you can see that the item size does not matter really
every time i run tests, result is different. i agree with @JonasWilms answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.