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

Use binary search in insertToPriorityArray #17444

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions packages/ckeditor5-utils/src/inserttopriorityarray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,20 @@ export interface ObjectWithPriority {
export default function insertToPriorityArray<T extends ObjectWithPriority>( objects: Array<T>, objectToInsert: T ): void {
const priority = priorities.get( objectToInsert.priority );

for ( let i = 0; i < objects.length; i++ ) {
if ( priorities.get( objects[ i ].priority ) < priority ) {
objects.splice( i, 0, objectToInsert );

return;
// Binary search for better performance in large tables.
let left = 0;
let right = objects.length;

while ( left < right ) {
const mid = ( left + right ) >> 1; // Use bitwise operator for faster floor division by 2.
const midPriority = priorities.get( objects[ mid ].priority );

if ( midPriority < priority ) {
right = mid;
} else {
left = mid + 1;
}
}

objects.push( objectToInsert );
objects.splice( left, 0, objectToInsert );
}