From e0ac655a2c4e2a09faff08b55fc0f73c99712741 Mon Sep 17 00:00:00 2001 From: Vishesh Handa Date: Thu, 19 Mar 2020 23:25:15 +0100 Subject: [PATCH] SortedNotesFolder: Massive optimization Use a binary search instead of sequential --- lib/core/sorted_notes_folder.dart | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/lib/core/sorted_notes_folder.dart b/lib/core/sorted_notes_folder.dart index 65bbcff7..90a87362 100644 --- a/lib/core/sorted_notes_folder.dart +++ b/lib/core/sorted_notes_folder.dart @@ -85,15 +85,28 @@ class SortedNotesFolder with NotesFolderNotifier implements NotesFolder { } int _insertInCorrectPos(Note note) { - var i = 0; - for (; i < _notes.length; i++) { - var n = _notes[i]; - if (_sortFunc(n, note) > 0) { - break; + var i = _getInsertPos(note, 0, _notes.length); + _notes.insert(i, note); + + return i; + } + + int _getInsertPos(Note note, int low, int high) { + int mid; + while (low <= high) { + mid = low + ((high - low) ~/ 2); + + var r = _sortFunc(_notes[mid], note); + if (r == 0) { + return mid; + } else if (r < 0) { + return low = mid + 1; + } else { + return high = mid - 1; } } - _notes.insert(i, note); - return i; + + return mid; } @override