// AS-IS
const dailyCalorieRepository = AppDataSource.getRepository(DailyCalorie);
await transactionRunner(async (queryRunner) => {
const bmiRepo = dailyCalorieRepository.create({
carbohydrate: carbohydrate,
protein: protein,
lipid: lipid,
calorie: calorie,
bmiId: foundBodyMassIndex.id,
foods: foods,
});
await queryRunner.manager.save(bmiRepo);
});
//TO-BE
await transactionRunner(async (queryRunner) => {
const insertedDailyCalorie = await AppDataSource.manager.insert(DailyCalorie, {
carbohydrate: carbohydrate,
protein: protein,
lipid: lipid,
calorie: calorie,
bmiId: foundBodyMassIndex.id,
foods: foods,
});
await queryRunner.manager.save(insertedDailyCalorie); // DB Commit
});
데이터를 create할 때, save() 메서드가 insert() 메서드보다 대용량 데이터일때 성능이 안좋다는 블로그를 봤다.
물론 save 메서드 내에서도 두번째로 전달된 엔티티 객체에 primary key로 전달된 값이 없으면 Insert를 수행하도록 코드를 작성할 수도 있다. 이 블로그를 참고하길 바란다.
기본적으로 사용되는 .save() 의 경우 upsert 를 지원하기 위해 insert 전에 항상 select 를 호출하는 등의 작업도 진행한다.
때문에 단순 데이터를 저장하는데도 많은 리소스를 사용하게 되고 insert 메서드와 성능차이가 2배까지도 차이날 수 있다.
요약
많은 데이터를 한번에 넣는 Bulk Insert를 사용해 데이터를 주고받는 횟수를 1회로 줄여 데이터베이스와 어플리케이션 간의 통신 비용을 낮추는 방법도 사용할 수 있다.
만약, 개별적인 데이터를 넣어야하는 경우(bulk insert를 못쓰는 경우) insert 메서드를 사용하는 것이 save 메서드보다 성능이 향상된다.
참고
insert vs save 성능차이 : https://jojoldu.tistory.com/689
insert, save, update, upsert 정리 : https://blog.naver.com/pjt3591oo/222978080727
'JaveScript > ExpressJS' 카테고리의 다른 글
redis connection timeout error (0) | 2024.04.11 |
---|---|
APM tool을 Expressjs에 연동하기 (0) | 2024.04.10 |
async/await 를 Promise.allSetted로 리팩토링하기 (0) | 2024.03.31 |
유효성검사 중복코드 리팩토링하기 (0) | 2024.03.26 |
if-else => switch-case 리팩토링 (0) | 2024.03.25 |