使用全局变量会影响MATLAB的性能吗? [英] Does using global variables impact performance in MATLAB?

查看:702
本文介绍了使用全局变量会影响MATLAB的性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,向其他函数发送参数时,MATLAB无法使用pass by reference.我正在做音频处理,经常需要将波形作为参数传递给函数,并且因为MATLAB将pass by value用作这些参数,所以这样做确实会占用大量RAM.

As I understand, MATLAB cannot use pass by reference when sending arguments to other functions. I am doing audio processing, and I frequently have to pass waveforms as arguments into functions, and because MATLAB uses pass by value for these arguments, it really eats up a lot of RAM when I do this.

我当时正在考虑使用global变量作为将波形传递给函数的方法,但是在我读过的所有地方似乎都普遍认为这对于代码的组织和潜在的性能问题来说是个坏主意. ,但是我还没有真正阅读任何有关如何影响性能的详细答案...

I was considering using global variables as a method to pass my waveforms into functions, but everywhere I read there seems to be a general opinion that this is a bad idea, for organization of code, and potentially performance issues... but I haven't really read any detailed answers on how this might impact performance...

我的问题:使用全局变量(大小大于100MB)将参数传递给MATLAB中其他函数的负面影响,无论是 1) 性能 2) 通用代码组织和良好做法.

My question: What are the negative impacts of using global variables (with sizes > 100MB) to pass arguments to other functions in MATLAB, both in terms of 1) performance and 2) general code organization and good practice.

从下面的@Justin答案来看,当您不修改函数中的参数时,MATLAB有时会使用按引用传递!由此,我有一个有关全局变量性能的第二个相关问题:

From @Justin's answer below, it turns out MATLAB does on occasion use pass by reference when you do not modify the argument within the function! From this, I have a second related question about global variable performance:

使用全局变量会比对函数使用pass by reference自变量慢吗?

Will using global variables be any slower than using pass by reference arguments to functions?

推荐答案

MATLAB 确实使用按引用传递,但也使用写时复制.也就是说,您的变量将通过引用传递到函数中(因此不会在RAM上加倍),但是如果您在函数中更改变量,则MATLAB将创建一个副本并更改该副本(保留原始的不受影响).

MATLAB does use pass by reference, but also uses copy-on-write. That is to say, your variable will be passed by reference into the function (and so won't double up on RAM), but if you change the variable within the the function, then MATLAB will create a copy and change the copy (leaving the original unaffected).

这个事实似乎还不太清楚,但是有一个

This fact doesn't seem to be too well known, but there's a good post on Loren's blog discussing it.

底线:听起来您根本不需要使用全局变量(如@Adriaan所说,这是一个坏主意).

Bottom line: it sounds like you don't need to use global variables at all (which are a bad idea as @Adriaan says).

这篇关于使用全局变量会影响MATLAB的性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆