Best alternative to MATLAB's global variables - performance

I'm writing a MATLAB application which has many functions spread over different files. I have a logger, which is a struct with a function pointer, and I use it to log information for the user to see (that is, which function is currently executing, calculation results, etc.). The reason I use a struct for my logger and not simply fprintf() is that I could easily replace it with an XML logger, HTML logger, etc. in the future.
Since my code is composed of many functions calling each other, I declared my logger struct as global, so I don't have to pass it to all my many functions. However, everywhere I look I see that global variables are evil incarnate in MATLAB and will slow my program down considerably.
Is there a way to have variables available across files without necessarily passing them as input parameters, and without suffering from severe performance penalty?

You can also use persistent keyword inside a file, and allocate the logger there.
It is similar in some ways to the static keyword in C++. It is also an implementation of the Singleton pattern.
function CallLogger(st)
persistent logger;
if isempty(logger)
%Allocate new logger
end
logger.disp(st);
end
It is better than global because
1. No one can destroy your logger without your knowledge.
2. No one even knows about this object, because it is limited to the function scope
By the way, I don't agree that global has a performance issue. It is just not a good practice, in terms of Software Engineering.

Better than invoking persistent variables in a function (which, for example, won't be saved if you save and then reload your workspace) would be to move from function + struct to object: that is, you should look into MATLAB's object oriented programming.

Related

Near-sdk-as Contracts - Singleton style vs Bag of functions

It seems like there are two styles for writing NEAR smart contracts in assembly script
Bag of functions like Meme Museum
Singleton style like Lottery.
I was wondering under what circumstance one style is recommended over the other.
When should you use one over the other? What are the advantages/disadvantages of each style?
The big differences is in initialization of the contract.
Bag of Functions (BoF)
For the first style, usually a persistent collection is declared at the top level. All top level code in each file is placed into a function and one start function calls each. The Wasm binary format allows to specify the start function so that anytime the binary is instantiated (e.i. loaded by a runtime) that function is called before any exported functions can be called.
For persistent collections this means allocating the objects, but no data is required from storage, until something is read, including the length or size of the collection.
Singleton
A top level instance of the contract is declared. Then storage is checked for the "STATE" key, which contains the state of the instance. If it is present storage is read and the instance is deserialized from storage. Then each "method" of the contract is an exported function that uses the global instance, e.g. instance.method(...), passing the arguments to the method. If the method is decorated with #mutateState then the instance is written back to storage after the method call.
Which To Use
Singleton's provide a nice interface for the contract and is generally easier to understand. However, since you are reading from storage at every method call, it can be more expensive.
The other advantage of the BoF is it's easier to extend as you can export more functions from a dependency.
However, it's also possible to use a combination of both as well.
So really it's whatever makes sense to you.

D / DLang : Inhibiting code generation of module-private inlined functions

I have a D module which I hope contains public and private parts. I have tried using the keywords private and static before function definitions. I have a function that I wish to make externally-callable / public and ideally I would like it to be inlined at the call-site. This function calls other module-internal functions that are intended to be private, i.e. not externally callable. Calls to these are successfully inlined within the module and a lot of the cruft is disposed of by CTFE plus known-constant propagation. However the GDC compiler also generates copies of these internal routines, even though they have been inlined where needed and they are not supposed to be externally callable. I'm compiling with -O3 -frelease. What should I be doing - should I expect this even if I use static and/or private?
I have also taken a brief look at this thread concerning GCC hoping for insight.
As I mentioned earlier, I've tried both using private and static on these internal functions, but I can't seem to suppress the code generation. I could understand this if a debugger needed to have copies of these routines to set breakpoints in. I need to stress that this could perhaps be sorted out somehow at link-time, for all I know. I haven't tried linking the program, I'm just looking at the generated code in the Matt Godbolt D Compiler Explorer using GDC. Everything can be made into templates with a zero-length list of template parameters (e.g. auto my_fn()( in arg_t x ) ), tried that, it doesn't help but does no harm.
A couple of other things to try: I could try and make a static class with private parts, as a way of implementing a package, Ada-style. (Needs to be single-instance strictly.) I've never done any C++, only massive amounts of asm and C professionally. So that would be a learning curve.
The only other thing I can think of is to use nested function definitions, Pascal/Ada-style, move the internal routines to be inside the body of their callers. But that has a whole lot of disadvantages.
Rough example
module junk;
auto my_public_fn() { return my_private_fn(); }
private
static // 'static' and/or 'private', tried both
auto my_private_fn() { xxx ; return whatever; }
I just had a short discussion with Iain about this and implementing this is not as simple as it seems.
First of all static has many meanings in D, but the C meaning of translation unit local function is not one of them ;-)
So marking these functions as private seems intuitive. After all, if you can't access a function from outside of the translation unit and you never leak an address to the function why not remove it? It could be either completely unused or inlined into all callers in this case.
Now here's the catch: We can't know for sure if a function is unused:
private void fooPrivate() {}
/*template*/ void fooPublic()()
{
fooPrivate();
}
When compiling the file GDC knows nothing about the fooPublic template (as templates can only be fully analyzed when instantiated), so fooPrivate appears to be unused. When later using fooPublic in a different file GDC will rely on fooPrivate being already emitted in the original source - after all it's not a template so it's not being emitted into the new module.
There might be workarounds but this whole problem seems nontrivial. We could also introduce a custom gcc.attribute attribute for this. It would cause the same problems with templates, but as it's a specific annotation for one usecase (unlike private) we could rely on the user to do the right thing.

Blocks vs delegates or blocks vs methods

I have just studied blocks it is good ,easy to use,helps in inline coding and keeps thing at one place .But I am not able to understand the following two points clearly.
1)How blocks are different from methods and delegates?
2)Advantages of using blocks over methods and delegates.Where are blocks more useful than delegates and methods.
Kindly explain and help me in understanding the concepts better.Thanks in advance!
A seemingly curious question as you ask:
1)How blocks are different from methods and delegates?
2)Advantages of using blocks over methods and delegates.Where are blocks more useful than delegates and methods.
After you wrote:
easy to use, helps in inline coding and keeps thing at one place
Regardless, though I maybe misunderstanding what you are after, here some further points to your own to consider in case they are helpful:
Instance methods and delegates are both associated with an instance of an object; so there is a self with instance variables, properties and other methods all of which can be referenced and used. Both come with accompanying state.
A block, like a function, is not associated with an instance of an object.
A block however differs from a function in that it can capture values and variables (those annotated with __block) from the method/function they are defined within. So they carry some state.
As to advantages of one over the others, it is really a question of picking the appropriate one for the scenario – none is "better" and the others. Decide what you need; adding behaviour to an object (method), passing an instance/method pair to provide some functionality (delegate), providing functionality based on values in the local scope (block), etc., etc.; and use the appropriate construct.
HTH

Alternatives to global variables

I have a program that will grab several global settings from an API when first logged in. These values are then used extensively throughout the program. Currently I am storing them in global variables, but it does not seem very OOP.
What are the alternatives to global variables for storing extensively used settings? Use constants? Class variables? Where would I initialize the values through the API call, since this would only need to happen once? I have seen some examples that instantiate a class to get to the variables but that does not make much sense to me.
I would like to set the values on login and after this call the variables everywhere else with a simple expression like Global.myvalue or GLOBAL_MYVALUE
The Singleton Pattern might be handy for this:
https://ruby-doc.org/stdlib-2.1.0/libdoc/singleton/rdoc/Singleton.html
It's hard to give you a concise answer based on the information you provided, but I would avoid using global variables at all costs.
A good starting point would be to think of a class that could be a common ancestor to all the places where you use these variables and store them in that class. If your subclasses inherit from that class, these variables will automatically be available in their context.
Edit: like #seph posted, the singleton pattern seems to be a much better solution though

Ruby: marshal and unmarshal a variable, not an instance

OK, Ruby gurus, this is a hard one to describe in the title, so bear with me for this explanation:
I'm looking to pass a string that represents a variable: not an instance, not the collection of properties that make up an object, but the actual variable: the handle to the object.
The reason for this is that I am dealing with resources that can be located on the filesystem, on the network, or in-memory. I want to create URI handler that can handle each of these in a consistent manner, so I can have schemes like eg.
file://
http://
ftp://
inmemory://
you get the idea. It's the last one that I'm trying to figure out: is there some way to get a string representation of a reference to an object in Ruby, and then use that string to create a new reference? I'm truly interested in marshalling the reference, not the object. Ideally there would be something like taking Object#object_id, which is easy enough to get, and using it to create a new variable elsewhere that refers to the same object. I'm aware that this could be really fragile and so is an unusual use case: it only works within one Ruby process for as long as there is an existing variable to keep the object from being garbage collected, but those are both true for the inmemory scheme I'm developing.
The only alternatives I can think of are:
marshal the whole object and cram it into the URI, but that won't work because the data in the object is an image buffer - very large
Create a global or singleton purgatory area to store a variable for retrieval later using e.g. a hash of object_id:variable pairs. This is a bit smelly, but would work.
Any other thoughts, StackOverflowers?
There's ObjectSpace._id2ref :
f = Foo.new #=> #<Foo:0x10036c9b8>
f.object_id #=> 2149278940
ObjectSpace._id2ref(2149278940) #=> #<Foo:0x10036c9b8>
In addition to the caveats about garbage collection ObjectSpace carries a large performance penalty in jruby (so much so that it's disabled by default)
Variables aren't objects in Ruby. You not only cannot marshal/unmarshal them, you can't do anything with them. You can only do something with objects, which variables aren't.
(It would be really nice if they were objects, though!)
You could look into MagLev which is an alternative Ruby implementation built on top of VMware's Gemstone. It has a distributes object model wiht might suit your use-case.
Objects are saved in the central Gemstne instance (with some nifty caching) and can be accessed by any number of remote worker instances. That way, any of the workers act on the same object space and can access the very same objects simultaneously. That way, you can even do things like having the global Garbage Collector running on a single Ruby instance or seamlessly moving execution at any point to different nodes (while preserving all the stack frames) using Continuations.

Resources