I found a really strange bug when changing an object name property, then sort an array. It is very slow ! And i don't understand why...
I've made it simple here when clicking on files: stackblitz sort bug (please use firefox, because chrome does not even make it...)
My Object :
export interface MyFile {
name: string;
}
I've got a simple Html file like this :
<div *ngFor="let file of filesA" (click)="sortA(file)">
{{ file.name }}
</div>
<div *ngFor="let file of filesB" (click)="sortB(file)">
{{ file.name }}
</div>
I init files here :
ngOnInit() {
for (let i = 0; i < 20000; i++) {
this.filesA.push({ name: 'File A' + i });
}
this.sortFile(this.filesA);
for (let i = 0; i < 20000; i++) {
this.filesB.push({ name: 'File B' + i });
}
this.sortFile(this.filesB);
}
I've got a method that sort a list by name
sortFiles(files: MyFile[]): void {
files.sort((a, b) => {
return a.name.localeCompare(b.name);
});
}
Then, I've got two cases scenarios :
filesA : changing the name, then sorting the list (like everyone does).
sortA(file: MyFile) {
file.name = 'ZZ';
this.sortFile(this.filesA);
}
filesB : create a clone, remove the file, insert the clone, change the name of the clone, then sorting the list.
sortB(file: MyFile) {
const clonedFile: MyFile = Object.assign({}, file);
this.filesB.forEach((removeFileB, index) => {
if (removeFileB.name != clonedFile.name) return;
this.filesB.splice(index, 1);
});
clonedFile.name = 'ZZ';
this.filesB.push(clonedFile);
this.sortFile(this.filesB);
}
file.name = 'AA';, then it's fast...Do you have any suggestions not having to clone the object ? (which is pretty dirty) or this could be a critical bug on Angular ?