MySQL vs PostgreSQL 简单性能对比

Cing
发布于 2021-12-19 / 373 阅读
0

MySQL vs PostgreSQL 简单性能对比

环境

软件

  1. MySQL 8.0.27
  2. PostgreSQL 14.1

硬件

  1. 阿里云轻量服务器 2C2G

建表

MySQL

create table test
(
    id   int auto_increment
        primary key,
    name varchar(50) default '' not null
);

PostgreSQL

create table test
(
    id   bigint generated always as identity
        primary key,
    name varchar(50) default ''::character varying
);

因为是简单的对比所以不对参数做调整
除了批量模式给 MySQL 增加 rewriteBatchedStatements=true 的参数

对比

单条循环插入

code

    public void run(String... args) {
        List<Test> testList = new ArrayList<>(1000);
        for (int i = 0; i < 1000; i++) {
            Test test = Test.builder().name(RandomUtil.randomString(10)).build();
            testList.add(test);
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (Test test : testList) {
            testService.save(test);
        }
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

对比

MySQL

MySQL 普通循环 1000 条记录
---------------------------------------------
ns         %     Task name
---------------------------------------------
19696884400  100%  

PostgreSQL

pg 普通循环 1000 条记录
---------------------------------------------
ns         %     Task name
---------------------------------------------
8587525200  100%  

批量保存

code

    public void run(String... args) {
        List<Test> testList = new ArrayList<>(10000);
        for (int i = 0; i < 10000; i++) {
            Test test = Test.builder().name(RandomUtil.randomString(10)).build();
            testList.add(test);
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 使用 Mybatis-Plus 的批量保存
        testService.saveBatch(testList);
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

MySQL

注意给 MySQL 增加批处理参数rewriteBatchedStatements=true

mysql 无批处理参数 10000 条记录
---------------------------------------------
ns         %     Task name
---------------------------------------------
65295293000  100%  
mysql 有批处理参数 10000 条记录
---------------------------------------------
ns         %     Task name
---------------------------------------------
960313300  100%  
1023085200  100%  

PostgreSQL

pg 默认 10000 条记录
---------------------------------------------
ns         %     Task name
---------------------------------------------
1153501400  100%
1169868600  100%

结论

在不做任何修改的情况下,PostgreSQL 的性能无论是 for 循环插入还是批量模式均快于 MySQL。在 MySQL 加入了批处理参数后在批量存储时,有小幅优势