Skip to content

Commit

Permalink
Performance: Improve method for removing items from the mutable array (
Browse files Browse the repository at this point in the history
  • Loading branch information
jborkowski authored Apr 12, 2024
1 parent ffa7889 commit 44c06fa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
30 changes: 23 additions & 7 deletions src/Specular/Internal/Incremental/MutableArray.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,45 @@
// empty :: forall a. Effect (MutableArray a)
export function empty() {
return [];
return { array: [], nullCnt: 0 };
}

// push :: forall a. EffectFn2 (MutableArray a) a Unit
export function push(self, x) {
self.push(x);
self.array.push(x);
}

// remove :: forall a. EffectFn2 (MutableArray a) a Unit
export function remove(self, x) {
var index = self.indexOf(x);
var index = self.array.indexOf(x);

if (index !== -1) {
self.splice(index, 1);
self.array[index] = null;
self.nullCnt++;
}
}

// length :: forall a. EffectFn1 (MutableArray a) Int
export function length(self) {
return self.length;
return self.array.length - self.nullCnt;
}

// iterate :: forall a. EffectFn2 (MutableArray a) (EffectFn1 a Unit) Unit
export function iterate(self, fn) {
for (var i = 0; i < self.length; i++) {
fn(self[i]);
let writeIndex = 0;

// Clean up array using in-place filtering technique
for (let i = 0; i < self.array.length; i++) {
const value = self.array[i];
if (value !== null) {
fn(value);
if (writeIndex !== i) {
self.array[writeIndex] = value; // Move non-null values to the left
}
writeIndex++;
}
}

// Trim the array to remove null values
self.array.length = writeIndex;
self.nullCnt = 0;
}
4 changes: 0 additions & 4 deletions src/Specular/Internal/Incremental/MutableArray.purs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,11 @@ import Prelude

import Effect (Effect)
import Effect.Uncurried (EffectFn1, EffectFn2)
import Unsafe.Coerce (unsafeCoerce)

foreign import data MutableArray :: Type -> Type

foreign import empty :: forall a. Effect (MutableArray a)

unsafeToArray :: forall a. MutableArray a -> Array a
unsafeToArray x = unsafeCoerce x

foreign import push :: forall a. EffectFn2 (MutableArray a) a Unit
foreign import length :: forall a. EffectFn1 (MutableArray a) Int

Expand Down

0 comments on commit 44c06fa

Please sign in to comment.