Sometimes you need to create temporary files. Usually, you can discard those temporary files by opening them in a fashion so they are deleted when they are closed. However, in some cases, you are dealing with a library or other class that is very picky about what you give it. Other times, you create an entire directory and want that directory to be deleted when you application is closed.
Whatever the case, there are several approaches to this. The first and most obvious (to me) was to try to use C#/.NET’s Disposable interface pattern. By creating a static List of those objects, we can ensure their Dispose()/Finalizers are run when the application is terminated (static variables and fields are disposed when the application is being torn down). Then the logic to delete and attempt to delete the file can be placed in the Dispose() method as needed. My implementation originally encountered problems with sharing violations- since the application, early on, may have many handles open. Primarily, this likely occurs because of the non-deterministic nature of how static objects are disposed; so if a File is opened and is in another static member, it might not have been disposed when our dispose method is called. As a result I’ve added a Delayed invoke method which, if the delete fails initially, will call itself again after a second (trying up to five times).
This implementation also gives up after a few tries and then tries to schedule the file for reboot deletion. I considered a rather insane mechanic whereby the class would store a data file in the Temporary folder, then when first constructed (eg. static constructor) it can check for that file and either create and dispose a DeletionHelper for each filename stored in that data file, or add those files to the existing list for deletion when the application terminates. However, after considering it I figured such a feature might make things more complicated than necessary.
The other idea for automatic deletion would be to use the CreateFile() API with full share permissions, and pass the FILE_FLAG_DELETE_ON_CLOSE flag to it, then close that file in the Dispose method. Here is one possible implementation:
And so, that gives us two implementations. I currently use the first in BASeBlock for deleting the temporary files and folders that are sometimes created during start-up, particularly if it finds a Zip file (which may have additional content that it checks for). Since those extracted files may be used during the run, I use the class to make sure they are deleted when the Application exits; or at least make an effort to do so.
70 total views, 2 views today
Integrated Development Environments. These are the programming tools that most of us have come to almost take for granted. They provide the ability to write, debug, edit, and otherwise develop our software within a cohesive software product. You can find Development Environments for nearly every language platform. Microsoft Visual Studio can handle C#, VB.NET, F#, and C++ out of the Box, while also providing a wealth of other language capabilities through aftermarket software. Java has Eclipse and Netbeans, just to name two- the list goes on.
However, for every IDE user, there is a person who ‘looks down’ on the lowly IDE user; “they aren’t actually writing code” they grumble into their bag of cheetos- they are simply selecting things from an autocomplete list. These types of people are, perhaps in a statistically significant way, usually users of *nix based systems. They extoll the virtues of their favourite text editor- emacs, vim, nano, and look down on IDEs, which they will sometimes refer to as “glorified text editors”.
If my patronizing tone in the previous paragraph was not obvious- or if you’ve never read one of my programming-oriented blog entries, I’m firmly on the side that supports and uses IDEs, wherever they are available. The arguments against them are often lame; arguing that getting used to a feature like autocomplete or parameter lists, or dynamic help windows, and tips and whatnot make us “soft” is absurd- the same could be said of keyboards- by extension it just makes inputting data easier, so clearly we should be flipping switches manually. My point is that IDE software aims to make the task of software development easier, and more productive. And IMO it does this is spades.
There are even add-ins for many IDEs that basically provide all sorts of world-class capabilities in the IDE. Resharper is one exceptional such plugin that is available for Visual Studio- at this point, if it’s missing, it’s like I’m missing an appendage. It has made my work in Visual Studio so much more enjoyable and productive, that I almost feel it’s a crime not to have it installed. Similar addons are available for all sorts of IDEs; even Visual Basic 6 has things like MZTools(Free) or AxTools CodeSMART(Commercial).
Of course, IDEs lose a lot of their edge in certain languages, particularly those that lean towards the dynamic end of the spectrum. So much information about the program relies on run-time, that it’s a tricky proposition for a piece of software to try to figure out what is going on and provide any sort of tips or suggestions. Unsurprisingly, most of those that find IDEs childish use languages such as Python, Perl, Ruby, and PHP; I myself do not use an IDE for these languages either; primarily because I couldn’t find one (VS 2012 has an add-in available called “PHP Tools” that apparently brings support for PHP, though I do not know the extent of it’s assistance). However, if there was a software product available that provided the same level of assistance to languages like Ruby and Python as I currently get from Visual Studio or Eclipse, I would jump on it like Mario on a Goomba.
We ought to think of the software as not only our tools, but our own assistants. Most people wouldn’t raise any objections about being given a personal assistant for their work or daily tasks. In the case of Resharper specifically, that assistant is also an 11.
176 total views, 2 views today
C#’s linq(language-integrated query) features are some of the more powerful features available through the language. Aside from it’s query operators that are, as it’s name would suggest, integrated into the language, the feature also brings along a large set of Extension methods to the IEnumerable
One interesting re-use of the IEnumerable
What we have here is similar- but not quite the same- as a switch statement within a loop. What makes this particularly interesting as a structure is that it acts sort of like a seive. The source to the extension EachCase() method is shown here:
The function works by calling the passed Action for all entries in the enumeration that cause TestExpression to return true. Those that return false are yielded to the caller. In the original code the EachCase() calls were chained, one after the other; each one operated on the entries that the previous one didn’t work with. the final .Count() call in the original code is to force it to be enumerated, allowing all the code blocks to evaluate appropriately. What use-cases might this have? I have no idea. However I feel confident in saying that it could make for a more readable alternative to something that might otherwise require a separate Finite-State machine.
320 total views, no views today
Most application frameworks/languages provide access to the Command Line parameters passed to your application. Generally it is passed to your application as either a string or an array of strings. What you do not get automatically is the functionality to parse out switches.
Command-line parameters used to be the only way to communicate with a program. Fundamentally, the command line was your UI into the program. Different platforms took different approaches. Unix-like systems typically take the “invasive” route; they replace wildcards and then pass the resulting command line to the application. This means that you don’t have to do any shell expansion of wildcards (as it is known) but you have to account for the fact that your command line could include a lot of files. It’s a trade-off, really. Either way, I figured for the purposes of this library, we could stick to the platform- if the program is run with a wildcard, you’ll see the wildcard on windows, but it will have been expanded if you run the same program on Linux. It might be worth adding an option to “auto-expand” wildcards- just for consistencies sake, but that seems like a post for another day.
Either way, most applications also include flags and switches. This is more a De Facto standard that has cropped up- there is no hard and fast rulebook about what flags and switches are or how you are supposed to pass arguments, which can cause no end of confusion when it comes to reading application documentation. the .NET language just gives you the string, and leaves it up to you to decide how to interpret it. Some language libraries provide functionality to parse the Command Line appropriately, such as Python. C# doesn’t come with such a class…. So let’s make one!
First we need to determine what exactly can exist in a command line. My method allows for two things: Switches, and arguments. A Switch can include an argument, separated from the switch with a colon. For example:
In this case, we have three switches- switch, sw, and doall. The first two include an argument. My “syntax” allows for quotes in the arguments of switches as well as the “loose” arguments. We will evidently need classes to represent and parse Arguments, and another one for Switches. The parsing can be done sequentially. Although it’s not a recommended best practice, I chose to use by reference parameters in the class constructors. In order to keep things generic and accessible, both Switches and Arguments will derive from a CommandLineElement abstract class, which will force each base class to implement toString(). the ArgumentItem class will be used for parsing both “loose” arguments, as well as arguments found after a switch.
Arguments are simple- if the first letter of the position is a quote, we look for the next quote that isn’t doubled up. Otherwise, we look for either the next whitespace or the end of the string. Each argument only needs the actual argument value.
The constructor is where the important stuff happens. the by reference parameter is used to define the starting position, and we update it when the constructor returns to point at the character after the argument. The class also defines some statics for implicit conversions to and from a string.
Now that we have the Argument class, we can define the Switch class. The actual syntax of switches often depends on the application but also seems to depend on the platform. for example, Linux tools favour the hyphen for single letter flags, and double hyphens for multi-character flags. Switches are also called flags. forward slash is not generally used as a switch or flag indicator. Windows platforms prefer the forward slash but generally allow for single hyphens as well. We aim to support all three syntaxes, and make the client application not have to worry about which it is. We also add support for arguments- a switch can be specific as such:
someprogram /d:argument.exe
The element after the colon will be parsed as an argument and attached to the switch itself. But enough waffling- on to the Switch:
With the basic parsing logic completed, we need to consider how we want this to be used. Best way is to think of how we would like to use them:
Some basic take-aways from this. First, the Core Parser Object needs to provide an Indexer. In the above example, we see it is accessing Switches by passing in the Switch name. Other possibilities include using direct numeric indexes to refer to any argument- much like you would access elements in the framework provided args [] String array. Another possibility is to have the Argument of a switch auto-populate, rather than be null, when accessed:
1,154 total views, 50 views today
The following consists of my opinion and does not constitute the passing on of an official statement from Microsoft. All thoughts and logic is purely my own and I do not have any more ‘insider’ information in this particular topic than anybody else
I’ve been hearing from the community a bit of noise about Microsoft’s XNA Framework- a Programming library and suite of applications designed to ease the creation of Games- being cut. A google reveals a lot of information, but a lot of it is just plain old rumours. The only one I could find that was based on actual information still makes a lot of assumptions. It is based on this E-mail:
Our goal is to provide you the best experience during your award year and when engaging with our product groups. The purpose of the communication is to share information regarding the retirement of XNA/DirectX as a Technical Expertise.
The XNA/DirectX expertise was created to recognize community leaders who focused on XNA Game Studio and/or DirectX development. Presently the XNA Game Studio is not in active development and DirectX is no longer evolving as a technology. Given the status within each technology, further value and engagement cannot be offered to the MVP community. As a result, effective April 1, 2014 XNA/DirectX will be fully retired from the MVP Award Program.
Because we continue to value the high level of technical contributions you continue to make to your technical community, we want to work with you to try to find a more alternate expertise area. You may remain in this award expertise until your award end date or request to change your expertise to the most appropriate alternative providing current contributions match to the desired expertise criteria. Please let me know what other products or technologies you feel your contributions align to and I will review those contributions for consideration in that new expertise area prior to the XNA/DirectX retirement date.
Please note: If an expertise change is made prior to your award end date, review for renewal of the MVP Award will be based on contributions in your new expertise.
Please contact me if you have any questions regarding this change.
This is an E-Mail that was sent out- presumably- to XNA/DirectX MVPs. I say presumably because for all we know it was made up to create a news story. If it was sent out, I never received it, so I assume it would have been sent to those that received an MVP Award with that expertise. It might have been posted to an XNA newsgroup as well. Anyway, the article that had this E-mail emblazoned as “proof” that MS was abandoning XNA seemed to miss the ever-important point that it actually says nothing about XNA itself, but actually refers to the dropping of XNA/DirectX as a technical Expertise. What this means is that there will no longer be Awards given for XNA/DirectX development. It says nothing beyond that. Now, it could mean they plan to phase it out entirely- but to come to that conclusion based on this is a bit premature, because most such expertise-drops actually involved a merge. For example, in many ways, an XNA/DirectX expertise is a bit redundant, since XNA/DirectX works using a .NET Language such as VB.NET and C# and very few XNA/DirectX MVPs truly can work with XNA in any language at all, it might make sense to just clump them with us lowly Visual C# and Visual Basic MVPs.
To make the assumption that XNA is being dropped based on this E-mail is a bit premature. In my opinion, I think the choice was made for several reasons. I guess some of the misconceptions might be the result of misconceptions about just what a Microsoft MVP is. First, as I mentioned before, a lot of the expertise of XNA/DirectX involves an understanding- and expertise- in some other area. Again, Visual C#, Visual Basic, Visual C++, etc. So in some ways they might have considered a separate XNA/DirectX expertise redundant. Another reason might have to do with the purpose of an MVP. MVP Awards are given to recognize those who make exceptional community contributions in the communities that form around their expertise. For example, my own blog typically centers around C#, solving problems with C# and Visual Studio, and presents those code solutions and analyses to the greater community by way of the internet, as well as sharing my knowledge of C# and .NET in those forums in which I participate. MVP awardees don’t generally receive much extra inside information- and that they do get is typically covered by a NDA agreement. The purpose of the award is to also establish good community members with which Microsoft can provide information to the community. MVPs are encouraged to attend numerous events where they can, quite literally, talk directly to the developers of the Products with which they acquainted. in some way you could consider MVPs “representatives” of the community, who are chosen because their contributions mean they likely have a good understanding of any prevalent problems with the technologies in question, and interacting with MVPs can give the product teams insight into the community for which their product is created. Back to the particulars here, however- as the E-mail states, XNA Game Studio is not under active development. Now, following that, it seems reasonable to work with the assumption that either that product has no Product Team, or those that are on that Product Team are currently occupied in other endeavours, or other products for which their specific talents are required.
It’s not so much that they are “pulling the plug in XNA”- the product is currently in stasis. As a direct result of this, it makes sense that without an active Product Team, having specific MVP Awardees for that expertise isn’t particularly useful for either side- MVPs gain from personal interactions with the appropriate Microsoft Product team as well as fellow MVPs, and Microsoft gains from the aggregate “pulse of the community” that those MVPs can provide. Without a Product Team for a expertise, that expertise is redundant, because there is nobody to get direct feedback. This doesn’t mean the XNA community is going away, just that, for the Moment, there is no reason for Microsoft to watch it’s pulse, because the product is “in stasis” as the OS and other concerns surrounding the technology metamorphize and stabilize (The Windows 8 UI style, Windows Store, and other concerns in particular). Once the details and current problems with those technologies are sussed out, I feel they will most certainly look back and see how they can bring the wealth of game software written in XNA to the new platform. Even if that doesn’t happen, XNA is still heavily used for XBox development- which is also it’s own expertise.
I hope this helps clear up some of the confusion that has been surrounding XNA. It doesn’t exactly eliminate uncertainty- this could, in fact, be a precursor to cutting the technology altogether. But there is nothing to point to that being the direction, either.
460 total views, no views today
Randomization is something that is pretty much a staple in games. But the tricky part is randomizing in an expected way.
Some kinds of randomization, you don’t want to be truly random- just mostly random- and you do in fact want it to go through all the possibilities more frequently, though in a random way.
The best example I can think up is to imagine you have a Enemy that can shoot forwards, backwards, up, and down. Now, targeting the player notwithstanding, let’s assume you want them to shoot randomly. If you go with the approach of just choosing a direction completely at random, you will find that the code will often choose the same direction many times in a row. This is more or less the problem with trying to randomize small sets of data. Each selected element is more or less chosen without regard to those chosen before. This fits probability, of course, but can be a bit weird gameplay wise.
The solution is fundamentally to make sure that items are chosen at random, but also that every item get’s used. The best solution I could think of was one where you choose elements at random, but you make sure you don’t choose the same elements twice during any one run. The class I created for this purpose I called “CItemBucket”. It’s functionality is fairly simple: it is constructed with the items it will contain. This initializes two lists with those elements. The ItemBucket can “dispense” items; when an item is dispensed, it is removed from the list. if the list is empty, it is reset from the Original List. this makes sure that in any number of elements of size N, any element in that list will occur exactly once during N dispenses. My original idea was to return a randomly indexed element each call, but then I got to thinking that, in many ways, we are simply dealing with a “shuffled deck” of elements, and returning items from that “deck”. So, at the cost of making Adding a bit more expensive, I think I was able to make the retrieval method O(n) for the number of present elements (based on the Queue implementation, that is).
Here, the, is the C# Implementation for this class:
Here is some code that consumes this implementation:
Works quite well, as far as I can tell.
Perhaps because I like to think of myself as something of a polyglot, let’s go ahead and come up with an implementation of this for Java. Now, doing this in Java would be a bit more tricky- that is, directly. Unlike the C# implementation, we don’t have the convenience of lambda’s to make a ‘pure’ shuffle. Instead, we would have to write our own implementation. Instead of that, I went with the original concept- that is, to choose,remove, and return a random index, and re-create the Bucket contents when we’ve emptied it. Here is the Java version of this class:
Test code for the above Java implementation:
As far as I’m concerned, the most interesting thing in the Java implementation is the “RepeatArray” method. Java’s Generic limitations prevent us from creating Arrays of the Generic Type Parameter directly, so instead we need to use some reflection magic. unfortunately, as far as I can tell there is no way to get the class of the actual type parameter in Java, so I had to resort to accepting that class as a parameter. Also, because of the lack of Generators/Enumerable methods, I ended up simply having that method return a List of the generic type, rather than an Enumerable.
You might think, “OK, he’s covered C# and Java implementations- can I please go home. Well, yes, you can. But then you’ll miss my Python implementation! I went with the same approach I chose for Java- that is, retrieving items randomly and removing them. It’s fully possible to use the same methodology I used for the C# approach- using Queues and sorting on randomized keys- but I found this approach a bit less verbose, and more straightforward. And, it is my opinion that ‘straightforward’ is sort of the “python way”, so I went with that.
And, of course, the Python code that uses it:
The first thing that stands out is just how much shorter this one is to either the Java or C# implementations. This is probably mostly due to the dynamic typing of Python, as well as a few syntactic shortcuts. The only “gotcha” I found was that Python didn’t really support overloaded methods. Technically, I could create one method and then verify what parameters were actually passed, but in this case I wanted one to be a Generator Method, and the other to simply return a single element. Only way I could figure out how to do that was to have separate DispenseSingle() and DispenseMulti() methods. It also doesn’t expose the innards like the other implementations, in that you cannot add Elements to an already constructed instance. In retrospect, I’m not really sure if it’s a good idea to make the design Mutable at all. The Most typical use-case would be to construct it with all the elements it will use, and not change it afterwards- that’s the use case I have in BASeBlock, and the use-case I’m considering using my Java implementation for. So having extra methods to add elements, and keep fields “fresh” and consistent adds implementation complexity for little gain.
606 total views, no views today
One common problem that comes up in the creation of stylized windows such as Splash screens is the desire to have parts of the form be “shadowed” or, in other words, blend with the forms behind them. You can see this effect in action with other application splash screens, such as photoshop:
What witchcraft is this? How does Photoshop do it? One of the first things you might try with .NET is something like the TransparencyKey of the form. Of course, this doesn’t work, instead you get this unsightly ring of the transparency key around it.
The solution, of course, is a bit more complicated.
Starting with Windows 2000, the Win32 API and Window Manager has supported the idea of “layered” Windows. Before this, Windows had concepts known as “regions”; this basically allowed you to define regions of your window where the background would show through. This didn’t allow for per-pixel blending, but that sort of thing was not widely supported (or even conceived of, really) by most graphics Adapters. The “Layered” Windowing API basically provided a way to allow Per-pixel Alpha. Which is what we want.
Windows Forms, however, does not expose this layered window API through it’s methods or properties, with the exception of the opacity property. I don’t recall if WPF does either, but I would be surprised if it’s capabilities exposed more of the Layered Windowing API. Basically- we’re on our own
So what exactly do we need to do? Well, one thing we need to do is override the CreateParams property of the desired form, so that it adds the WS_EX_LAYERED style to the window, letting the Windowing Manager know it has to do more work with this window. Since we would like a neatly decoupled implementation, we are going to create a class that derives from Form, but use that as the base class for another form. This let’s us override the CreateParams property within that base class, but this has a bit of a caveat as well, since I’ve found that makes the Designer a bit annoyed and it complains and won’t let you use the designer. So you will have to deal with that particular point yourself. (I imagine there is a way to make it work, but I don’t want to bloat the class with such functionality). If necessary, the appropriate functions and the CreateParams override can be put into the classes that need this functionality instead.
Here is the PerPixelAlphaForm class. By the way, I’m going with Visual Basic.NET because there are already a million hits for this functionality with C#:
This provides the core implementation. The “Win32″ class here provides the needed API declarations.
In order to use this, we need to make our form derive from it, and then use the inherited SetBitmap function:
(Here I just used an image on my second Hard disk that had a transparency channel, but the Bitmap constructor parameter can easily be changed.). The result:
The Project I used for this can be downloaded from here . This was created using Visual Studio Professional 2012, Update 1- other editions or earlier versions may have problems with the project or source files.
1,002 total views, 4 views today
Though I do tend to try to write my samples and test applications, as well as any new programs, using Visual Studio 2012, I haven’t yet migrated most of my other applications to it. For BASeBlock and BCJobClock, for example, they started off in Visual Studio 2008. More recently, I migrated them to Visual Studio 2010. BCJobClock had it’s project upgraded to Visual Studio 2012, (but for some reason the admin applet doesn’t work on Windows 8, which is something that certainly bears further investigation). Anyway, I’ve been strongly considering it the more I think about it. In particular, I’ve found Visual Studio 2010 to actually be a lot slower. Originally, I thought this was because my 201 install had several add-ins installed, such as ReSharper, but now that I also have a version of ReSharper that works with Visual Studio 2012, I still find 2012 to be far more responsive.
Now VS2012 has gotten some flak from certain users for adopting the Windows 8 UI style into it’s icons, as well as using Caps in it’s menus. I really have no strong preference here at all, and I personally don’t see what the fuss is about. I’ve heard people say that the capitals “hurt their eyes” but I can honestly say that I don’t understand how that could be the case.
Anyway: I’ve been considering switching BASeBlock over the Visual Studio 2012. If I do I won’t be upgrading the project to use the 4.5 framework, though. At least not yet.
262 total views, no views today
Undo/Redo Stacks
The BASeBlock Editor has had an Undo/Redo stack for quite a while. The implementation of this logic is relatively simple, but the implementation- or rather, my recent re-implementation- seems like a good subject for a blog post.
Basically, an Undo/Redo Stack Let’s your Program reverse through changes that have been made, and then, if necessary, go forward through those changes. What makes this problem interesting is that, by and large, the core logic is really quite similar. I will attempt to outline the process of creating a Generic Undo/Redo Object that can be used in many contexts.
First, we’ll start with The abstract base class that we will use to represent Undo Elements:
Since we don’t know what, specifically, is being handled, we use this abstract class and provide only very basic methods. The DateTime can be used on appropriate menus or as a sort key, and the Description can be used for any menu text, or other UI elements as needed by the app consuming the class.
This will be used for a generic class, which I will call UndoRedoManager. This will, unsurprisingly, manage the undo and redo operations, or, more specifically, it will manage the data structures dealing with the Undo and Redo information. In order to actually undo, we will need to delegate the task to the caller, on the assumption that they know more about the StackItem. We will call the Events HandleRedo and HandleUndo, and they will take a simple EventArgs. First, we will define the EventArgs class definition.
The Event Argument class is relatively simple; we just have a field for the StackElement, and a field for Cancel, which we will deal with when we fire the event. We use a generic class because we need to support the management of any class type that derives from UndoRedoStackItem, where the appropriate application-specific data will be dealt with and stored.
The “UndoRedoManager” class we will create will be designed as generically as possible. And, to be honest, my original implementation will be a naive one, each Stack Element will be designated as storing a complete “state” for whatever the application is doing. A better approach for applications that have a large amount of state data is to instead store the changes, rather than the entire thing, but that sort of extra functionality is best discussed and designed after we have the basic framework in place.
The first step is to designate what we need to keep track of in the ‘Manager’ Class, as well as our events.
We need a Maximum size, otherwise it’s possible for the stack to fill up with old Undo elements. We keep a stack for Undo as well as Redo elements. The actual public functionality we need to implement is a method to Undo, a Method to Redo, and a Method to “Push” a new element onto the Undo stack (register a change).
We’ll start with the first method that will usually be used: PushUndo. This will accept a parameter that is the type of the generic type parameter. It will need to:
Here is the code to do that. TrimStack() is private method who’s implementation I will cover shortly:
Most of this is self-explanatory. TrimStack’s implementation is a bit trickier, since the Stack
TrimStack here is written to take any Stack Type, though, arguably, this isn’t necessary in this current implementation. (No reason, however, to make it more specific, in my opinion)
First, if the stack has fewer elements than the passed maximum, we have no work to do, so we return right off the bat. Making our work quite easy.
If the Stack does have more elements than the maximum, we pop elements until either the stack to trim is empty (for some reason) or the temporary stack has maxelements elements.
The effect here is to grab the top maxelements items. After this, we clear the stack and push the elements we popped.
The task of performing the Undo has the following steps:
The idea here is that the Event handler that is tied to the class will do the application-specific activity for the “undo” operation- we don’t know what the data is, nor what it represents, but the program using us will, so we leave them to it. This also enables the less naive implementation concept that I’ll be using later to extend this.
And that is pretty much the core implementation. Of course, as it is, we don’t actually have an implementation for the StackElement class. Since that is something we left up to the client application, let’s create one. Here is a small Windows Form that utilizes the aforementioned classes as well as providing an implementation of the Stack Item for a TextBox:
The Designer class:
Proper code-behind class:
In the above implementation, TextUndoItem is the UndoRedoStackItem implementation I created for textboxes; this stores the selection start and length as well as the full text. The Actual Undo implementation was less trivial than I had hoped; in this case I created a “Managing” class that uses the UndoRedoManager specifically with Textboxes, hooking the appropriate textbox events and implementing a delay after typing stops before Undo’s are pushed onto the stack. This is a very simple implementation of this particular class design; BASeBlock uses a very similar class in it’s Editor, but for the far more complex structures dealt with there, which include several lists of objects.
The extension and addition to this design that I mentioned earlier consists of storing not the entire state, but rather what changed from the previous element. This is unlikely to be a trivial thing to implement.
740 total views, no views today
This is not another entry into the series regarding anagrams, but a much simpler synopsis using a very basic algorithm. The performance of programming languages and technologies are cited by a lot of people as being “slow” or “faster” or any number of terms of the sort. Recently, I’ve been told that Flash/ActionScript is “slow”. Now, I am not doing this to prove that wrong- in fact I think the results may prove that to be the case- but rather to show something that has been repeated several times by others.
First, the algorithm. In order to keep things simple, we’ll make the algorithm simple as well- it will simply generate a random number a million times and put it into an array or list.
The ActionScript version. This is ActionScript 2.0 since I only have Flash 8 installed:
Elapsed time was 7586 milliseconds (or 7.5s).
Now, to another language: let’s go with python for the moment.
This doesn’t even finish in 10 minutes. Clearly we’ve proven that Python is really slow, correct? Not really, no:
The reason the previous one was slow was because of how Python works. The line arr = arr + [random.random()] was allocating a new list and assigning it to the list. The old one was freed for garbage collection. The big problem was that as it went on those allocations got larger and larger. The above uses the append() method of the list, which adds it to the end of the same list- rather than creating a new one each time. The resulting execution time? 340 milliseconds or so.
OK, let’s move on to C:
This one is a bit messy since I couldn’t get the clock() stuff working, it always gave me a negative value, so I just included windows.h and used GetTickCount() instead. An interesting side-note is that I originally declared the array of int’s statically, as in:
Hilariously, though- that failed catastrophically, causing a StackOverflowException in the run-time itself when the program started. I had to switch it to dynamic allocation as shown above. The error makes sense since locals are normally stored on the stack; using malloc() puts them on the heap instead. Unsurprisingly, this implementation results in a run-time of 34 milliseconds.
What do we conclude? Well, first, it’s important to realize that C is simply less maintainable than Most other languages; this means that the “faster” implementation is going to take quite a bit longer to write, and it’s going to be more effort to maintain as well as add features too. Additionally, by virtue of it leaving far more responsibility in the hands of the programmer, it is more likely for bugs to creep in. Various controls, such as code reviews and standards can mitigate these concerns, but they cannot eliminate them completely. My point is that using C over a high-level language is not a magic bullet for a faster application, but requires more programmer time in terms of writing and maintaining the code to begin with, and is additionally more susceptible to bugs through that maintenance. In this instance, we are looking at over 34 times the speed. But, the only important concern is whether that speed difference matters. Another thing is that the Python implementation could likely be made even faster too- I didn’t fully explore that; either through code changes, or through the use of another python interpreter or compiler technology. Basically unless speed is actually an issue and it can be traced directly to the chosen language platform- and there is no way to mitigate the problem- does it make sense to choose a language like C, or even C++.
504 total views, 2 views today

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 