百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

为什么MySQL存储过程、函数和触发器对性能不好

toyiye 2024-07-02 03:04 22 浏览 0 评论

MySQL存储过程、函数和触发器是应用程序开发人员的诱人构造。但是,正如我所发现的,使用MySQL存储例程会影响数据库性能。由于不能完全确定在客户访问期间看到了什么,我开始创建一些简单的测试来度量触发器对数据库性能的影响。结果可能会让你大吃一惊。

为什么存储例程在性能上不是最佳的:短版本?

最近,我与一位客户合作,了解触发器和存储例程的性能。我对存储例程的了解是:“死”代码(分支中的代码永远不会运行)仍然可以显著降低函数/过程/触发器的响应时间。我们需要小心地清理我们不需要的东西。

Profiling MySQL Stored Functions

Let's compare these four simple stored functions (in MySQL 5.7):

Function 1

CREATE DEFINER=`root`@`localhost` FUNCTION `func1`() RETURNS int(11)

BEGIN

declare r int default 0;

RETURN r;

END

This function simply declares a variable and returns it. It is a dummy function.

Function 2

CREATE DEFINER=`root`@`localhost` FUNCTION `func2`() RETURNS int(11)

BEGIN

declare r int default 0;

IF 1=2

THEN

select levenshtein_limit_n('test finc', 'test func', 1000) into r;

END IF;

RETURN r;

END

This function calls another function, levenshtein_limit_n (calculates levenshtein distance). But wait: this code will never run — the condition IF 1=2 will never be true. So that is the same as function 1.

Function 3

CREATE DEFINER=`root`@`localhost` FUNCTION `func3`() RETURNS int(11)

BEGIN

declare r int default 0;

IF 1=2 THEN

select levenshtein_limit_n('test finc', 'test func', 1) into r;

END IF;

IF 2=3 THEN

select levenshtein_limit_n('test finc', 'test func', 10) into r;

END IF;

IF 3=4 THEN

select levenshtein_limit_n('test finc', 'test func', 100) into r;

END IF;

IF 4=5 THEN

select levenshtein_limit_n('test finc', 'test func', 1000) into r;

END IF;

RETURN r;

END

Here there are four conditions and none of these conditions will be true: there are 4 calls of "dead" code. The result of the function call for function 3 will be the same as function 2 and function 1.

Function 4

CREATE DEFINER=`root`@`localhost` FUNCTION `func3_nope`() RETURNS int(11)

BEGIN

declare r int default 0;

IF 1=2 THEN

select does_not_exit('test finc', 'test func', 1) into r;

END IF;

IF 2=3 THEN

select does_not_exit('test finc', 'test func', 10) into r;

END IF;

IF 3=4 THEN

select does_not_exit('test finc', 'test func', 100) into r;

END IF;

IF 4=5 THEN

select does_not_exit('test finc', 'test func', 1000) into r;

END IF;

RETURN r;

END

This is the same as function 3, but the function we are running does not exist. Well, it does not matter as the selectdoes_not_exit will never run.

So, all the functions will always return 0. We expect that the performance of these functions will be the same or very similar. Surprisingly, that is not the case! To measure the performance, I used the "benchmark" function to run the same function 1M times. Here are the results:

+-----------------------------+

| benchmark(1000000, func1()) |

+-----------------------------+

| 0 |

+-----------------------------+

1 row in set (1.75 sec)

+-----------------------------+

| benchmark(1000000, func2()) |

+-----------------------------+

| 0 |

+-----------------------------+

1 row in set (2.45 sec)

+-----------------------------+

| benchmark(1000000, func3()) |

+-----------------------------+

| 0 |

+-----------------------------+

1 row in set (3.85 sec)

+----------------------------------+

| benchmark(1000000, func3_nope()) |

+----------------------------------+

| 0 |

+----------------------------------+

1 row in set (3.85 sec)

As we can see, func3 (with four dead code calls that will never be executed, otherwise identical to func1) runs almost 3x slower compared to func1(); func3_nope() is identical in terms of response time to func3().

Visualizing All System Calls From Functions

To figure out what is happening inside the function calls, I used performance_schema/sys schema to create a trace with ps_trace_thread() procedure.

1.Get the thread_id for the MySQL connection:

mysql> select THREAD_ID from performance_schema.threads where processlist_id = connection_id();

+-----------+

| THREAD_ID |

+-----------+

| 49 |

+-----------+

1 row in set (0.00 sec)

2.Run ps_trace_thread in another connection passing the thread_id=49:

mysql> CALL sys.ps_trace_thread(49, concat('/var/lib/mysql-files/stack-func1-run1.dot'), 10, 0, TRUE, TRUE, TRUE);

+--------------------+

| summary |

+--------------------+

| Disabled 0 threads |

+--------------------+

1 row in set (0.00 sec)

+---------------------------------------------+

| Info |

+---------------------------------------------+

| Data collection starting for THREAD_ID = 49 |

+---------------------------------------------+

1 row in set (0.00 sec)

3.At that point I switched to the original connection (thread_id=49) and run:

mysql> select func1();

+---------+

| func1() |

+---------+

| 0 |

+---------+

1 row in set (0.00 sec)

4.The sys.ps_trace_thread collected the data (for 10 seconds, during which I ran the ), then it finished its collection and created the dot file:

+-----------------------------------------------------------------------+

| Info |

+-----------------------------------------------------------------------+

| Stack trace written to /var/lib/mysql-files/stack-func3nope-new12.dot |

+-----------------------------------------------------------------------+

1 row in set (9.21 sec)

+-------------------------------------------------------------------------------+

| Convert to PDF |

+-------------------------------------------------------------------------------+

| dot -Tpdf -o /tmp/stack_49.pdf /var/lib/mysql-files/stack-func3nope-new12.dot |

+-------------------------------------------------------------------------------+

1 row in set (9.21 sec)

+-------------------------------------------------------------------------------+

| Convert to PNG |

+-------------------------------------------------------------------------------+

| dot -Tpng -o /tmp/stack_49.png /var/lib/mysql-files/stack-func3nope-new12.dot |

+-------------------------------------------------------------------------------+

1 row in set (9.21 sec)

Query OK, 0 rows affected (9.45 sec)

I repeated these steps for all the functions above and then created charts of the commands.

Here are the results:

Func1()

Func2()

Func3()

As we can see, there is a sp/jump_if_not call for every "if" check followed by an opening tables statement (which is quite interesting). So parsing the "IF" condition made a difference.

For MySQL 8.0 we can also see MySQL source code documentation for stored routines which documents how it is implemented. It reads:

Flow Analysis OptimizationsAfter code is generated, the low level sp_instr instructions are optimized. The optimization focuses on two areas:

Dead code removal,Jump shortcut resolution.These two optimizations are performed together, as they both are a problem involving flow analysis in the graph that represents the generated code.

The code that implements these optimizations is sp_head::optimize().

However, this does not explain why it executes "opening tables." I have filed a bug.

When Slow Functions Actually Make a Difference

Well, if we do not plan to run one million of those stored functions, we will never even notice the difference. However, where it will make a difference is ... inside a trigger. Let's say that we have a trigger on a table: every time we update that table it executes a trigger to update another field. Here is an example: let's say we have a table called "form" and we simply need to update its creation date:

mysql> update form set form_created_date = NOW() where form_id > 5000;

Query OK, 65536 rows affected (0.31 sec)

Rows matched: 65536 Changed: 65536 Warnings: 0

That is good and fast. Now we create a trigger which will call our dummy func1():

CREATE DEFINER=`root`@`localhost` TRIGGER `test`.`form_AFTER_UPDATE`

AFTER UPDATE ON `form`

FOR EACH ROW

BEGIN

declare r int default 0;

select func1() into r;

END

Now repeat the update. Remember: it does not change the result of the update as we do not really do anything inside the trigger.

mysql> update form set form_created_date = NOW() where form_id > 5000;

Query OK, 65536 rows affected (0.90 sec)

Rows matched: 65536 Changed: 65536 Warnings: 0

Just adding a dummy trigger will add 2x overhead: the next trigger, which does not even run a function, introduces a slowdown:

CREATE DEFINER=`root`@`localhost` TRIGGER `test`.`form_AFTER_UPDATE`

AFTER UPDATE ON `form`

FOR EACH ROW

BEGIN

declare r int default 0;

END

mysql> update form set form_created_date = NOW() where form_id > 5000;

Query OK, 65536 rows affected (0.52 sec)

Rows matched: 65536 Changed: 65536 Warnings: 0

Now, lets use func3 (which has "dead" code and is equivalent to func1):

CREATE DEFINER=`root`@`localhost` TRIGGER `test`.`form_AFTER_UPDATE`

AFTER UPDATE ON `form`

FOR EACH ROW

BEGIN

declare r int default 0;

select func3() into r;

END

mysql> update form set form_created_date = NOW() where form_id > 5000;

Query OK, 65536 rows affected (1.06 sec)

Rows matched: 65536 Changed: 65536 Warnings: 0

However, running the code from the func3 inside the trigger (instead of calling a function) will speed up the update:

CREATE DEFINER=`root`@`localhost` TRIGGER `test`.`form_AFTER_UPDATE`

AFTER UPDATE ON `form`

FOR EACH ROW

BEGIN

declare r int default 0;

IF 1=2 THEN

select levenshtein_limit_n('test finc', 'test func', 1) into r;

END IF;

IF 2=3 THEN

select levenshtein_limit_n('test finc', 'test func', 10) into r;

END IF;

IF 3=4 THEN

select levenshtein_limit_n('test finc', 'test func', 100) into r;

END IF;

IF 4=5 THEN

select levenshtein_limit_n('test finc', 'test func', 1000) into r;

END IF;

END

mysql> update form set form_created_date = NOW() where form_id > 5000;

Query OK, 65536 rows affected (0.66 sec)

Rows matched: 65536 Changed: 65536 Warnings: 0

Memory Allocation

Potentially, even if the code will never run, MySQL will still need to parse the stored routine-or trigger-code for every execution, which can potentially lead to a memory leak, as described in this bug.

结论

存储的例程和触发器事件在执行时被解析。即使是永远不会运行的“死”代码也会显著影响批量操作的性能(例如,在触发器中运行时)。这也意味着通过设置“标志”(例如)禁用触发器仍然会影响批量操作的性能。

对Java微服务、分布式、高并发、高可用、大型互联网架构技术、面试经验交流感兴趣的。可以关注我的头条号,我会在微头条不定期的发放免费的资料链接,这些资料都是从各个技术网站搜集、整理出来的,如果你有好的学习资料可以私聊发我,我会注明出处之后分享给大家。欢迎分享,欢迎评论,欢迎转发!

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码