Java 200 times faster, almost as easy to use, so why Javascript ?

    Javascript

    Alexandre's icon
    Alexandre's icon
    Alexandre
    Sep 01 2010 | 7:36 pm
    Since 5 years that I made these little efficiency tests (attached here), there have been many discussion on the forum about javascript vs java vs C, and the feeling that often comes out - false, i think - is illustrated by this Emmanuel Jourdan sentence :
    "JavaScript is slower than Java indeed, and Java is slower than C. That's in term of CPU/memory usage. In term of development time, it's about the inverse..." ( https://cycling74.com/forums/max-vs-java-vs-javascript-speed )
    CPU :
    Javascript execution is not only 3, 10 or 20 times slower than java, it IS between 200 times and 400 times slower than Java, in my test: In 4 millisec., my little test calculation loop is computed only 200 times in js, while 40000 times in java, on my MBP. (As probably every 'interpreted' code, max patchers execution is also around the same speed, 200 times slower than Java.) Now Java is about 1,5 slower than the C test (non-block-calculation), which, in most situations, is almost nothing. Ok for java, there is this JVM bridge little bottleneck every time that you cross an inlet/outlet, which is around 1 microsecond. Ok that's not always negligible, but well, when you make an mxj or javascript object, ...you are making your loops inside it, so you're not supposed to [uzi] very fast over it... By crossing this JVM bridge the less often possible, for example by joining numbers into list before sending thru an inlet/outlet (which mean crossing this bridge only once) i'm then really peaceful with this bridge, since 5 years, and there's no point for me to go to C.
    Now, Development time :
    To me, if you use it to make some max objects the same way you would using Javascript, Java is as easy to learn. (It will only be more complex to learn if you want to go further thru "inheritance" concepts and stuff... to things you can't do with javascript.) Now, using the great Eclipse developing environment for Java - far better than the Java editor inside max - the development time should be - at least - AS FAST AS Javascript. The assisted editing make it even more convenient than javascript. Just the syntax is a little bit different from Javascript but it's not few more semicolons that are gonna slow you down. About C, beside its slower development time, a real pain is that, from what i understood, you have to restart max every time you modify your object. ( https://cycling74.com/forums/how-to-load-rebuilt-external-without-reopening-max ) Not the case in java and javascript where you can refresh the max object.
    There's a great 'Step by Step Instructions tutorial' from Adam Murray, to use Eclipse with max: http://compusition.com/web/articles/maxmsp-eclipse
    ...in just a half an hour process, you're into java... So why Javascript ?
    I understand that the Javascript field is non-timing-sensitive stuff*, like UI related code, but in the beginning era of multi-touch - cf. http://www.youtube.com/watch?v=tfvEV1zcAjQ - then even UI related routines are going to be called more and more often, then even for that, Javascript could bring signifiant slow down, compared to java, in the future.
    5 years ago, I remember a discussion with jkc saying he liked javascript, but 5 year after i'm still asking myself why.
    I don't get why so much maxers are using Javascript and C, while fewer are using Java. ( 2 times more messages on the Javascript forum than on the Java forum ) Perhaps it's just a lack of publicity ? i'm making it... :-)
    P.S : But there is again worst than javascript: look at the [coll] object efficiency in the 'test-on-arrays'...
    * in the WritingMaxExternalsInJava.pdf doc : "For timing sensitive events the js and jsui objects should not be used"
    1058.Efficiency-Tests-Nov2005.zip
    zip

    • Noob4Life's icon
      Noob4Life's icon
      Noob4Life
      Sep 01 2010 | 8:13 pm
      "I don't get why so much maxers are using Javascript and C"
      C is still faster. '1.5 times' is not an absolute measure for everything... and it can make a big difference very fast in the development of larger apps.
      as for javascript, i'm not an expert and i do shy away from it(in Max) because i like C better, but it's the same argument as trying to say that you are happy to use Java even though you know C is faster. there's different situations suited for different things. there are situations where javascript does not take up much CPU at all. in those situations, the ease of quick scripting is applicable as an adequate substitute for lower-level programming.
      also, you develop C externals outside of Max, true, therefore you have to restart, but to me it's a negligible amount of time, when people talk of 'slower development time' for C, that's completely subjective: usually more true for those who are just plain slow at using their IDE and at programming in C.
      you make a good argument about javascript and java but your PPC compiling of C externals in your test while most are using intel these days and your arguments against C(while C is the cornerstone of how everything in Max was originally created), takes away from your argument by distracting it from the java/javascript relation alone and also may lead one to wonder why you've avoided the subject of C++ altogether.
      It is good to hear your passion for Java, though!
      Share
    • AlexHarker's icon
      AlexHarker's icon
      AlexHarker
      Sep 01 2010 | 8:29 pm
      I guess it really depends what you are trying to achieve.
      I have and do use all three. I don't think there is a good argument for only using one.
      If you (in many cases meaning me) are really serious about efficiency then C is probably the best way to go. 1.5x might be significant if you are writing audio code that is already expensive.
      Java has cross-platorm on it's side (that's the big plus for me).The garbage collection is a lot easier, but I'm not usually worried about cross-platform - I know the C API very well, and I can deal with garbage collection, so normally the speed wins out - when compatibility is a concern then java is normally my choice.
      Javascript is slow, but sometimes it's just the easiest. I use js a lot when I have an esoteric thing that I can't quite do in max, but the js API allows and I'm not going to want to reuse it a lot and speed is not a concern. Learning time for a language is not the only speed concern. I can write a quick routine in js in under 2 minutes and have it running. I doubt I could be as fast in java or C, even working from a template. THat is what development time means - not how long it takes for you to learn how to do it.
      The last thing which you fail to consider is the API available in each. One of the quirks of developing for max is that the APIs are all different. That means that sometimes it's really straightforward to do something in one, and not in another. Let's say I want to read a textfile without character limitations in. I did it in js in less than 20 lines. I don't think I've ever written an external in java or C that was anywhere near that compact.
      Great that you feel Java suits you, but each to his own. I can't help but think that when suitable, javascript is normally fastest to code, and often that is what counts.
      Just my take on it,
      Alex
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 01 2010 | 9:18 pm
      Noob4Life, you are right about C efficiency can be better than '1.5 times' specially for block calculation (audio externals, jitter). Sorry I don't have the intel version compiled for the C test because it was made for me by a guy at ircam five years ago. I doubt the '1.5 times' would change a lot anyway.
      > AlexHarker : "I can write a quick routine in js in under 2 minutes > and have it running. I doubt I could be as fast in java, even working from a template.
      from a template, that's 3 minutes for Java...
      > One of the quirks of developing for max is that the APIs are all different.
      Considering the too limited time that C74 team have to develop the full max API for each language, i feel that pattr and UI support for Java, instead of Javascript, might have been the best choice, for a real-time-sound-and-image software where efficiency and timing is an eternal question.
    • AlexHarker's icon
      AlexHarker's icon
      AlexHarker
      Sep 01 2010 | 9:44 pm
      By the way. I'm not sure I believe your figures totally.
      Try the below. this would seem to indicate that js slightly less than twice as slow on my computer (around 2000 milliseconds plays 3300 ish). Bang the little button...
      Can you confirm your results and comment. I haven't had time to check your patch in detail but this is a simple tried and tested way of measuring speeds. I'm on intel so I didn't do the c compile...
      Assuming my figures are right (which they may not be) that would somewhat change everything no?
      A.
      Max Patcher
      In Max, select New From Clipboard.
      Show Text
    • AlexHarker's icon
      AlexHarker's icon
      AlexHarker
      Sep 01 2010 | 10:02 pm
      My bad - I see now that you loop fois * 10 in the java code and fois / 10 in the js. Confusing but fair enough - that would account for the factor of 100.....
    • Jesse's icon
      Jesse's icon
      Jesse
      Sep 01 2010 | 10:10 pm
      Considering the too limited time that C74 team have to develop the full max API for each language, i feel that pattr and UI support for Java, instead of Javascript, might have been the best choice, for a real-time-sound-and-image software where efficiency and timing is an eternal question.
      ++ to mxj supporting pattr integration! Hoping it is coming soon.
    • Roman Thilenius's icon
      Roman Thilenius's icon
      Roman Thilenius
      Sep 01 2010 | 10:40 pm
      any use of javascript and java inside maxmsp should be illegal.
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 02 2010 | 8:11 am
      Yes AlexHarker, It was necessary to put this /10 for js and *10 for java and c, in order to avoid: 1- minutes to wait for the js to compute, 2- eventual bad precision over java an C if the test is too short. Then the compute time is corrected by multipling by this factor. (third [chrono] inlet in my patch). Sorry if my test then looks a bit complex.
      >> ++ to mxj supporting pattr integration! Hoping it is coming soon.
      Do you really think that could come soon? This would be nice. But looking at theses old topics ( https://cycling74.com/forums/pattr-support-in-max-5 and https://cycling74.com/forums/notifyclients-in-java ), it doesn't look like coming soon.
      >> any use of javascript and java inside maxmsp should be illegal. What should be illegal is the use of patch cords for sequential and algorithmic stuff. Looking at other people algorithmic patches just give me headaches. What i made in Java would have cost 10 time more developing time using patch cords. Keep max for its best: Real time events, audio, UI.
    • AlexHarker's icon
      AlexHarker's icon
      AlexHarker
      Sep 02 2010 | 1:26 pm
      Yes - I guessed as much once I'd figured that out.
      I get about 160 times faster here on a dual 3.0GHz MBP.
      FWIW - the javascript calculations as far as I know are double precision - the java ones are not. I wouldn't want to speculate too much on what difference it would make, but I think you'd see it in the figures.
      Obviously, single precision in javascript is not an option, but it would be better to compare like with like as far as possible...
      I can't help but feel however, that you are looking at large data, large loops within loops situations that may not be typical uses of javascript. I'm not going to disagree that js is bad for this, but in small applications I think you might find that worrying about cpu usage is a waste of energy. After all - if you have a process that takes 1% of your processor (for example) in a scenario where you are running at around 67% - then when you speed that up by 200 times you simply won't see it clearly in the results - so it's not good economy. If it takes up 40% of your processor however....
    • AudioMatt's icon
      AudioMatt's icon
      AudioMatt
      Sep 02 2010 | 1:36 pm
      "Any use of javascript and java inside maxmsp should be illegal. "
      I've broken the law. rehabilitate me. someone! I've been trying to get started with C/Max for 5 years now. never got off the ground. Why? The thing I've had problems with in every language isn't the language part but the way it's set up on in the OS. There are never any details about it in any tutorial. There's always a line "find foo.baz.clib on your drive" and it's never there. I've spent four years programming mxj externals and I have no frick'n clue what ANT is, how to write scripts for it, or where "java" is on my drive. I open eclipse, include max.jar and I'm done.
      Maybe that makes me not a "real" programmer. I couldn't care less.
      I'll try again soon when I get around to installing snow leopard but setting up max and C has taken weeks of my life and I've never gotten it right.
      That comes off ranty.. but it's more a rant of desperation :-)
    • Roald Baudoux's icon
      Roald Baudoux's icon
      Roald Baudoux
      Sep 02 2010 | 2:14 pm
      I have used JS to develop two or three projects. As most of them were non -realtime I didn't care about efficiency. I chose JS essentially because I wanted to use the drawing capabilities of the JSUI object and because as a non-programmer (I mean no experience in any formal language outside Max, SuperCollider and GW-Basic). I also wanted the shortest possible learning curve.
      I had one project to create rhythmic patterns using JS. Reading the resulting data in real-time with JS produced tons of clicks while reading them from colls worked correcly (althought transition between Max4 and Max5 showed some reductions in performance for very fast MIDI rhythms).
      I have been thinking about learning C several times but I always postpone it.
      Just my 2 cents.
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 02 2010 | 5:29 pm
      > the javascript calculations as far as I know are double precision
      I even didn't know. in attachment is the version with double in java, which is 2 time slower, in fact. (good to know)
      I have a question: Is there anyone having a example patch that cannot be done using only floats precision ? (I've never used double, and whenever i use the Java.Math methods i immediately convert in float.)
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 02 2010 | 5:56 pm
      > but in small applications I think you might find that worrying about cpu usage is a waste of energy.
      The problem with small applications, is that they often get bigger, or that one day you need to load a bunch of them for a live or something, and then nothing is working as before and you don't know why.
      If we were talking about a factor of 1,5 or 2, then ok, worrying about cpu usage for that may be a waste of time for a small application. But we are talking about a factor which is between 100 and 400 (yes, 400, see my 'Efficiency-test-on-arrays.pat': the loop is computed only 1000 times in js, while 400000 times in java, on my MBP.) Compared with java, to me, javascript is mostly a waste of energy for the computer.
      ...Ecologists would even make javascript illegal, what about your computer carbon footprint? :-D
    • amounra's icon
      amounra's icon
      amounra
      Sep 02 2010 | 6:25 pm
      If MaxforLive already included LiveAPI integration for Java, I'd be on the bandwagon...for now I'll code it in js and convert it when it needs done.
      (actually, I guess it makes little difference since the LiveAPI is low-priority anyway)...
      Still...the link to the tutorial above is helpfull...I've already installed Eclipse and started reading about Java. There are several things I wrote in js before I had to convert them into pureMax because js was too slow. I'd much rather have them in a script language....editing algorithmic stuff in Max is like trying to popular music trends....
    • AlexHarker's icon
      AlexHarker's icon
      AlexHarker
      Sep 02 2010 | 6:34 pm
      Double precision is a real necessity in certain scenarios - for instance:
      phasor accumulation (for audio rate buffer playback for example) calculating certain filter coefficients accurately
      My personal experience of double precision critical situations is more in the domain of audio rate programming admittedly, but that is just me. You seem to be suggesting that doubles are unnecessary. I'm trying to suggest that everyone's needs are different, and if java is twice as slow with doubles (that is inline with what I expected) - then on my computer you are looking at closer to 75 - 80 times slower for js doing the same thing - which is a substantially different figure to 200. Sometimes the speed gains offered by C *really* matter to me, whereas to you it isn't worth it.
      As for arrays - sure - I didn't say it was fast, or good for that. However, in the event that you do very little in a function call and you make the function call lets say every 10ms (which is really quite often compared to a message-based musical timing) - the CPU you might be talking about is really not worth worrying about.
      Believe me II have spent many hours optimising cpu and memory usage - to the point of ridiculous obsession. I understand the drive, but rule 1 of optimisation is don't optimise. It has many disadvantages. Rule 2 is optimise what matters first. Let's take Chris Muir's simple FM patch from a recent thread. Turns out that mtof~ accounts for over 50% of the cpu that that patch consumes. I can spend all the time I want optimising other parts, but some of them are so negligible that I could put in hours and hours and never see any real gain. I replaced mtof~ with a more efficient alternative and the patch ran almost twice as fast (55% with 32 voices down to 28%)...
      Often I am using js for one off calculations / loading processes / things that happen maybe less than once a minute. Unless those operations are noticeable intensive then optimisation is not a concern.
    • Noob4Life's icon
      Noob4Life's icon
      Noob4Life
      Sep 02 2010 | 6:50 pm
      Alex wrote, "Often I am using js for one off calculations / loading processes / things that happen maybe less than once a minute. Unless those operations are noticeable intensive then optimisation is not a concern."
      ya, this is what i was trying to say... for such contexts, a quick scripting language(like JS/Python/etc.) seems better than any small efficiency gains you get from a lower-level language.
    • Hans Höglund's icon
      Hans Höglund's icon
      Hans Höglund
      Sep 02 2010 | 7:03 pm
      Oh please, the days of low-level languages for general purpose programming is over (should be anyway).
      Using C as an application language was never a good idea and still isn't. It was designed for system programming, and that is were low-level concepts such as direct access to memory should stay. The programming platforms of the future are probably going to be virtual machines supporting dynamic linking, JIT-compilation (which already beat AOT-compilers in speed) and garbage collection on the fly.
      One reason to use JavaScript over Java is that it is a functional and more expressive language. Another is that is has direct access to the Max scheduler and object system, which Java has not. If speed is an issue, you can switch to Rhino and compile it to JVM bytecode, which will execute at java speed (this would of course restrict you to the Java API).
    • Noob4Life's icon
      Noob4Life's icon
      Noob4Life
      Sep 02 2010 | 8:03 pm
      Hans Hoglund wrote: "Using C as an application language was never a good idea and still isn't." I think everytime people bring C into the debate between Java and Javascript, it's going to distract from credibility on other points(JMax is dead, btw). I agree with most of what you say, but this holds no water whatsoever considering we are all here because of an application called "Max" which was(and to a great extent still is) written in C.
    • Hans Höglund's icon
      Hans Höglund's icon
      Hans Höglund
      Sep 02 2010 | 8:45 pm
      @Noob4Life I have no problem using and relying on stable software. What concerns me is that the performance arguments is used to hold back the emancipation of new and better languages. I think it should be the other way around, we should look out for more expressive ways to program and then consider implementation.
      Of course Max was designed to connect C programs, that was the the accepted way to do real-time back then. Now we have other options, there are hundreds of languages with safe memory, lambdas and dynamic dispatch that are fast enough for real-time, many of which can be integrated in Max.
    • Noob4Life's icon
      Noob4Life's icon
      Noob4Life
      Sep 02 2010 | 10:15 pm
      "I think it should be the other way around, we should look out for more expressive ways to program and then consider implementation."
      well put! after all, all 'languages' serve the primary purpose of communicating and disseminating any form of information(efficiency concerns are not always paramount to communication). if we talk of the future, i believe all apps and data will be web-based eventually, and personal comps will only be a terminal to that network, this will actually be more affordable and will provide better access to information for even 3rd world countries... sounds dangerous to comprehend at first, but since i don't think google/verizon/microsoft will ever succeed in completely limiting/commodifying our access and presence on the web, it's very possible... therefore, i agree with all your statements of what options we have and will have.
    • Anthony Palomba's icon
      Anthony Palomba's icon
      Anthony Palomba
      Sep 02 2010 | 10:48 pm
      I have never really understood why people want to do time critical operations with Java. As a software developer designing a real-time system, the last thing I want to build into it are unknowns like garbage collection and byte interpreted instructions. That just adds unknown inefficiencies that keeps you from squeezing all the power you can out of your system.
      Max is an open architecture that allows you to insert your own objects in that audio and data signal path. It is supposed to be as efficient as possible. Implementing your algorithm in C is probably the best compromise between readability and effecienncy.
      But for doing UI stuff I think javascript is decent. Although I think python is a much better language. I hope that one day, Cycling74 will add native support for it. I would love to have access to SciPy in Max!
    • Noob4Life's icon
      Noob4Life's icon
      Noob4Life
      Sep 03 2010 | 1:07 am
      "python is a much better language. I hope that one day, Cycling74 will add native support" +1 4 Python!
    • Hans Höglund's icon
      Hans Höglund's icon
      Hans Höglund
      Sep 03 2010 | 1:15 am
      @Anthony Your arguments are just not valid. The JVM of 1990s were slow, modern implementations are not. GC and JIT are not "dumb overheads" but higly intricate compilation techniques that may actually yield better performance than a C compiler. That JVM's are slow is just a plain old myth.
      What Java has is a slow startup time (about 500 ms on my machine, and this happens once when you load your first Java class). This is not because of JIT, but because Java links everything dynamically. The benefits of this are so huge that I have no problems with a split-second startup delay.
      Furthermore I would argue that in a real-time application stability is more important than raw performance. In Java code you will never have a memory error except if you mess up concurrency. Use Clojure and you will not even have that.
    • Hans Höglund's icon
      Hans Höglund's icon
      Hans Höglund
      Sep 03 2010 | 1:19 am
      Also, why should we need to compromise readability to have efficiency? Why not use a language that has both? (Not that Java does).
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 03 2010 | 8:09 am
      >> Why not use a language that has both? Good question.
      >> But for doing UI stuff I think javascript is decent.
      Try ej.fonction.js from the ejies, put lot's of segments and manipulate the visualizations, then javascript is not decent anymore...
      >> readability
      Comparing a javascript code with the same thing done in java, to me, in general, that's nearly the same in term of readability. The situations were javascript really looks more "expressive", are not coming so often to me, looking at codes. (plus, the really nice way that Eclipse manage color for instruction types and highlight other variables when you type on one, makes java even more readable, in my personal experience.)
    • AlexHarker's icon
      AlexHarker's icon
      AlexHarker
      Sep 03 2010 | 11:20 am
      @Hans
      "I would argue that in a real-time application stability is more important than raw performance. In Java code you will never have a memory error except if you mess up concurrency. Use Clojure and you will not even have that."
      You obviously know your stuff, and I respect your opinion, but this argument at least is void if the programmer deals with memory allocation and access correctly. Also, as always YMMV with regards to the importance of raw performance. As we are dealing with a real time audio language here, and portable computer power is not infinite, I think it is clearly arguable that in some scenarios available processing power limits what is desirable, and therefore raw performance is highly relevant. In time critical situations 20% (as quoted in the linked article) slower may simply be unacceptable.
      In reality I simply don't believe that 20% is a typical figure for what is being discussed here (max external in java vs one in C). I'd be happy to be proved wrong, but I'll be sticking to C for efficient audio processing until then.
      Don't get me wrong, I'm not arguing against the use of java, I'm just think that any choice of language is based on a combination of factors, and there are clearly arguments in all directions - using the most appropriate language in the circumstances seems would be my approach, and for me that could result in using C, java or javascript.
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 03 2010 | 2:10 pm
      Me, I'm not arguing against the use of C, but let's feed these interesting debates : About C vs java, in the C74 WritingMaxExternalsInJava.pdf doc, page 43, from Topher La Fata :
      "A properly written Java signal processing external is typically about 1.5-2.5X slower than the equivalent external written in C. A lot of this depends on what sort of processing your external is doing. In most cases the more computationally expensive your external, the closer that the Java and C versions will be in performance. This is because the biggest overhead introduced by doing your signal processing in Java is in the context switching that occurs when the mxj~ bridge calls from C into your Java signal processing routine. The cost of this context switch is amortized across the amount of time you spend actually accomplishing your task, so the more expensive your task, the less relatively expensive is the cost of the context switch."
    • Noob4Life's icon
      Noob4Life's icon
      Noob4Life
      Sep 03 2010 | 2:36 pm
      "Me, I'm not arguing against the use of C," but then you go on to do just that. At least be truthful rather than hypocritical. (Also, the quote starts with the wording "typically" and "depends on what sort of processing your external is doing", so it's not an empirical statement whatsoever.)
      I think what everyone is doing here is only proving that developers are extremely high-maintenance people ;) The discussion is whittling into something uninteresting and convincing me to stay away from Java(since devs in that environ seem more desperate to talk sh!t about all others more than anyone else i've seen). What you've convinced me of, is that even though you don't think it's significant, C is still significantly faster than Java(because 1.5-2.5xfaster can make a very big cumulative difference to me).
    • Anthony Palomba's icon
      Anthony Palomba's icon
      Anthony Palomba
      Sep 03 2010 | 3:05 pm
      With all due respect Hans, I definitely see the merit of your argument. Java VM technology has certainly advanced in the last 10 years.
      But I feel a lot of these benchmarks people quote are perfect scenarios that don't really reflect the real time performance environemnt of an integrated system (memory latency, kernel i/o, graphics/audio interfaces). You can argue all you want about how some JVM does an FFT faster than C, but put it in a real world environment and I think you'll see different results.
      Arguable the most complex real-time audio/graphics system out there are console game systems like the PS3 and Xbox. Why hasn't Sony or nVidia, chosen Java as their development language/environment of choice? Because it is an inefficient language for that environment. Having done video game development for 7 years now, I know for a fact the tremendous work that goes into squeezing every drop of processing power out of these systems. You are interfaceing with DSPs, GPUS, pixel/vertex shaders, etc. Implementing things in Java would be a joke, I mean really.
      Why would I not want my Max patch to perform at the same level?
    • AudioMatt's icon
      AudioMatt's icon
      AudioMatt
      Sep 03 2010 | 5:31 pm
      Whatever happened to testability? in java, in javascript, and MAX MSP? Why don't we do comparisons to settle this please? This whole thread confuses me!
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 03 2010 | 7:22 pm
      > "and MAX MSP?" From what i remember when looked at it, i think Max-Msp execution speed is more or less the same than javascript execution speed. (or something between 0.5X-2X)
      To make it clear: I am NOT arguing anything against C. I just mean that to write externals, Java is almost as great - and really more simple to use in my personal point of view - in most of the situations that i encounter. Sorry, I would add 3 words to this sentence from my first post, which some can find provocative, if i could : "Now Java is about 1,5 slower than the C test (non-block-calculation), which, FOR MY PURPOSE, in most situations, is almost nothing." C is great, Java is great, Max is great, MMF for Ipad is super Great!, and we are all great people!
    • AudioMatt's icon
      AudioMatt's icon
      AudioMatt
      Sep 03 2010 | 7:24 pm
      I was just screwing around :-)
    • Noob4Life's icon
      Noob4Life's icon
      Noob4Life
      Sep 03 2010 | 9:22 pm
      "I was just screwing around :-)" no one blames you, either, it's getting hard to take this thread seriously.
    • Hans Höglund's icon
      Hans Höglund's icon
      Hans Höglund
      Sep 04 2010 | 3:10 pm
      Implementing things in Java would be a joke, I mean really.
      I think this is still the old prejudice, but no matter. Performance of JVM for critical tasks has and will countinue to be widely debated. Of course Max is fundamentlly a native environment and integration with any VM can never be entirely smooth.
      I always figured the main reason for JavaScript in Max was there to provide a more lightweight interface to patcher scripting.
    • DiGiTaLFX's icon
      DiGiTaLFX's icon
      DiGiTaLFX
      Sep 04 2010 | 11:38 pm
      Wow, a well timed article considering I've been thinking about this over the past few days. If I could add a little bit of a hypothetical situation though...
      It seems that we now have a lot of work being done on JavaScript engines, with the likes of Google's V8, Apple's Nitro and Mozilla's JägerMonkey. If one of these was implemented into Max, would there be enough of a performance gain to put it anywhere near level with Java? As I understand it, these new engines are starting to compile directly to bytecode rather than just interpreting.
    • Hans Höglund's icon
      Hans Höglund's icon
      Hans Höglund
      Sep 07 2010 | 2:50 pm
      @DiGiTaLFX Agreed, there are many promising new implementations. Personally i use Mozilla's Rhino and compile to JVM bytecode which runs like lightning. I am not doing real-time audio in it though ;).
    • amounra's icon
      amounra's icon
      amounra
      Sep 08 2010 | 7:54 am
      @Hans I've been checking this out....how much Java do you need to know to work in this manner? I am also not doing RT audio, but I need faster processing for arrays and such...I'd like to start working on some flocking/algorithmic stuff and the last time I did this sort of thing in js I ended up having to rewrite the whole routine in pure Max b/c it was just too slow...I'm thinking this might be a nice alternative, without having to spend the extra time on the front end learning a new language.
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 08 2010 | 8:12 am
      > " the extra time on the front end learning a new language."
      Does this look that much more complicated ?
    • Emmanuel Jourdan's icon
      Emmanuel Jourdan's icon
      Emmanuel Jourdan
      Sep 08 2010 | 8:54 am
      It definitely is Alexandre. For you it's not because you're used to it. If you look at the same thing in C, you could have the same conclusion, it's not really much more complicated, as long as you have the skill, time… That's the reason why there's the 3 approaches, they are not equivalent in term of performance, nor in term of knowledge required, development time, cross/platform... Just use the language you know, and if that's not fast enough switch to the next one ;-)
    • DiGiTaLFX's icon
      DiGiTaLFX's icon
      DiGiTaLFX
      Sep 08 2010 | 1:45 pm
      @alexandre agreed! Do you have the same code in C? I'd love to see a side by side comparison of all three languages.
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 08 2010 | 3:07 pm
      The code in C, "calcultest.c", is in the "Efficiency-Tests-Nov2005.zip" attached above, in the first post of this topic, although i think that it could really be shorter (not made by me - i don't use C - but by Diemo from Ircam 5 years ago).
      Also, Emmanuel is right that this js/java example above is a bit too simple. There ARE more differences between coding in Javascript and Java that are not shown here. I just posted it to show you that java is not so complicated. Like I say on my first message, and like AudioMatt meant, i think : To just use java for mxj externals, it's ok if you have a light knowledge* of its structure. (Inheritances,polymorphism,etc... After few years of using java for mxj externals, i'm just starting on theses concept now, but that's because my mxj externals start to have thousands of line of code..)
      And i doubt about what Emmanuel say about development time, that Java would be slower to code than Javascript: Can someone organize a big Java/Javascript coding competition and see the result ? :-) I'm wondering that if javascript is faster to code, that from really short... ...For an execution speed lost of a factor which is between 60 -to AlexHarker POV - and 400.
      * But you do need to learn a bit about some java stuff: primitive types, operators, cast, arrays and Java.Math class if need some math. This is 10% of my java learning book.
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Sep 08 2010 | 5:03 pm
      If it's difficult to imagine what *60 or *400 really mean, have a look at my modified version of Flies.maxhelp attached.
      Anything like this in a js object is, from far, impossible.
    • amounra's icon
      amounra's icon
      amounra
      Sep 08 2010 | 7:40 pm
      Nope...that doesn't look that much more complicated....but I'm guessing that everything I would normally do in js isn't going to translate quite as easily. I've gotten used to the way js types variables, and I know how its integration with Max works. Besides: a lot of the stuff I need to do, I've already written scripts in js for the routines. Being able to convert already written scripts fairly easily with something like Rhino sounds very convenient.
      I will learn Java...its merely a matter of when I will have the time. I'm also trying to tackle Python right now (and I have a more immediate need for it), which is all that much more confounded by the lack of a decent way to test in Live (I'm working on control_surface scripts). Plus, it goes back to my original post: since the majority of my work is with the Live API at present, there is no facility for accessing those objects directly with Java, nor any speed increase since the API can only be accessed low-priority.
    • Joshua Kit Clayton's icon
      Joshua Kit Clayton's icon
      Joshua Kit Clayton
      Sep 10 2010 | 4:37 pm
      FWIW, we are looking into having a much faster JS engine for the next major version of Max. Java, JavaScript, Python, Lua, and C are all great languages, each with their advantages and disadvantages. If we could easily support everything in all languages we would, but we have to balance our development and maintenance priorities.
    • amounra's icon
      amounra's icon
      amounra
      Sep 10 2010 | 10:31 pm
      That's worth quite a bit (but of course a bird in the hand is worth two in the bush)....
    • DiGiTaLFX's icon
      DiGiTaLFX's icon
      DiGiTaLFX
      Sep 11 2010 | 10:58 pm
      @Joshua Yay!!! :D
    • Brian Gruber's icon
      Brian Gruber's icon
      Brian Gruber
      Sep 12 2010 | 8:17 pm
      @Joshua Kit Clayton
      a thousand times yes. v8 with commonsjs modules support please :D ?
    • Joshua Kit Clayton's icon
      Joshua Kit Clayton's icon
      Joshua Kit Clayton
      Sep 13 2010 | 7:11 pm
      Probably not V8, since it doesn't support multithreading, and would require a complete rewrite of much of our code. Jaegermonkey is the one we're watching. Lets of great work happening there, and it's coming close to Nitro/V8 performance.
      -Joshua
    • efe's icon
      efe's icon
      efe
      Oct 21 2010 | 10:16 pm
      Nice discussion, very enlightening to hear such interesting opinions. For me java provides the big advantage of the possibility of reusing code and the access to very interesting libraries, such as those coming from Processing. I would love to see a more supported class-oriented approach on the SDK. Besides efficiency it is interesting to think what kind of new technology can be implemented or bridged inside max(i am thinking of openCL or the quartz technologies, for instance).
    • DiGiTaLFX's icon
      DiGiTaLFX's icon
      DiGiTaLFX
      Nov 03 2011 | 7:55 pm
      So now that Max 6 is out, I decided to run these tests again and see what the difference in performance of the JavaScript engine was. I get around 250 iterations in Max 5 and 650 iterations in Max 6. So that's a 2.5 times increase in performance! It's still way off of the ~27000 iterations I get from the Java VM (double) though...
      Would be interested to see if someone could port the test to jit.gl.lua object.
      DiGiTaLFX
    • amounra's icon
      amounra's icon
      amounra
      Nov 04 2011 | 8:14 pm
      mmmmmm :) That's good news, I'd love to hear some further confirmation of this....I've started doing stuff that needs to be fast in Java, but I still prefer the ease of js, and use it whenever possible.
      On the other hand, how much of the stuff that I reserve for Java (for speed) will be possible with ~gen now, I wonder?
      a
    • Joshua Kit Clayton's icon
      Joshua Kit Clayton's icon
      Joshua Kit Clayton
      Nov 11 2011 | 6:05 pm
      Just a quick comment and examples. Hopefully to illustrate some best practices in JS for improved performance.
      These JS files you've provided make heavy use of global variables, and even then ones which haven't been scoped with var, The former are slow, and the latter are even slower (and dangerous since they are values shared between instances).
      This is true for both the older spidermonkey JS implementation, as well as the new JIT compiled Jaegermonkey implementation. And in the new engine it's even more important for optimal JIT performance.
      I've taken a brief moment to revise your examples just comparing your JS with some improved JS files.
      Also, some of your examples had codepaths which could possibly be eliminated (e.g. a large loop which sets one variable over and over again, so in effect the only one necessary to set is the final loop value, or if those values are never used in the future, they don't need to be set at all). So they might not be accurate tests of read/write performance, but rather a test of deadcode elimination. I didn't have time to investigate whether or not this is the case.
      Finally, also when testing you need to execute a function a few times before JS will completely JIT compile, so be sure to execute a few times to get the optimum JIT compiled benchmark.
      That said, Java will be faster than JS. No question. I don't know of any of the new JS implementation which are as fast as the JIT compiled Java VM. Part of this is because of static typing and other language features.
      Javascript, however, gains all that nice small talky dynamic typing and binding goodness, and is in many ways more agile than programming in Java, as long as you don't trip yourself up in the many errors that can happen with dynamic binding when not carefully coded.
      Anyway, not trying to get into any language better than another conversation. While I personally mostly code in C, I'm language agnostic. Each language is great for its own reason.
      My results with your examples are below:
      Calculations test:
      Max 5: old global js:349 revised js:459
      Max 6: old global js: 913 revised js: 11875 (~13x speedup)
      Array Fill Test:
      Max 5: old global js:0.53 seconds revised js:0.33 seconds
      Max 6: old global js: 0.33 seconds revised js: 0.06 seconds (~5x speedup)
      Array Writing Test:
      Max 5: old global js:1658 revised js:3041
      Max 6: old global js: 2240 revised js: 6207 (~3x speedup)
      Array Reading Test:
      Max 5: old global js:1249 revised js:3325
      Max 6: old global js: 1684 revised js: 9278 (~5.5x speedup)
    • DiGiTaLFX's icon
      DiGiTaLFX's icon
      DiGiTaLFX
      Jan 10 2012 | 12:46 pm
      Thanks Joshua for those tips! It makes sense that the assumption that the most efficient way of doing something in one language would be the same in another is actually wrong now that I think about it!
    • DiGiTaLFX's icon
      DiGiTaLFX's icon
      DiGiTaLFX
      Mar 31 2012 | 5:17 pm
      So I decided to try run the calculations test in jit.gl.lua for a comparison there too. I've ported Joshua's revised js test to lua (as I believe lua likes local variables too) and have attached to the post.
      I was quite surprised that the result was less than half as fast as js in Max 6 :(
    • Wesley Smith's icon
      Wesley Smith's icon
      Wesley Smith
      Mar 31 2012 | 5:56 pm
      This doesn't surprise me too much. The JS object in Max6 is using a JIT compiler, which are good at optimizing math in tight loops. jit.gl.lua is using the stock Lua interpreter, which isn't JIT compiled. If JS was still using a non-JIT compiler, jit.gl.lua would be faster.
      There is a LuaJIT project, which is blazingly fast, particularly for these kinds of tests. If jit.gl.lua was using that, it would be as fast if not faster than JS in Max6. I'll add a feature request for LuaJIT.
    • DiGiTaLFX's icon
      DiGiTaLFX's icon
      DiGiTaLFX
      Mar 31 2012 | 6:36 pm
      Ooooo, that wasn't the response I was expecting! LuaJIT would be absolutely amazing :D
      Thanks for explaining the differences :)
    • Alexandre's icon
      Alexandre's icon
      Alexandre
      Aug 20 2012 | 4:26 pm
      Hi, I felt it's been a long time since i didn't complain about javascript :-) It seems to me that javascript object in max6 are about 10 times slower to load than in max5...
      It's less than a second to reload 200 objects of my .js in Max5, and between 5 and 10 seconds (sometimes 15) in max6. ...which probably means sometimes 80 milliseconds to load one single .js! Try the simple patch below in max5, then in max6: There are 200 little abstractions each containing a very simple js object: 1 - delete them all, 2 - then do command-z...
      We are redesigning simpler our modular instrument structure in java and max (with full automation, powerful presets and sequencing system*), and each of our hundreds of parameters are connected to a little abstraction to connect numberboxes and sliders to a main java mxj object**. We need to built a dynamic "path" for send and receive objects and java would have been fine and super fast for that, but unfortunately, in java we can't access to the "maxbox" containing the patcher :-| So we though about using javascript for that but that max6 reload slowness doesn't sounds good. So we finally wrote a c-external for our little abstractions to access to this "maxbox" stuff, which will be fine.
      ** I though about using pattr, but we prefer our "little-abstractions" system for several little reasons, two of them being that you cannot directly dump value changes in one place from hundreds of scripting-named objects without also writing a c-external for that, and that pattr have the reputation to be slower that [send] and [receive].
    • goto10's icon
      goto10's icon
      goto10
      Aug 23 2012 | 12:48 pm
      Hey- I posted this on another thread, but I think its appropriate here:
      Do you know if anyone has given any thought to implementing Google's v8 interpreter? Seems like its 8-10x as fast as spidermonkey. How hard would it be to make an external that references and autowatches a js file or an mxj with something like jav8?
    • Artur Dobija's icon
      Artur Dobija's icon
      Artur Dobija
      Sep 26 2021 | 7:08 pm
      After reading the whole discussion 11 years later, I feel that the original question was not answered (if I understood correctly):
      Why does the Max offers an extended support for JS rather than Java, which is not that harder to learn?
      Unfortunately, this thread turned into Java vs C dilemmas & nuances battlefield, which may be crucial for the developers, but not for artists that seek the best tools and means for their projects, the artists for whom an interactive tool as MaxMSP was created in first place. Unfortunately, not everybody has a potential or time to be both. Some may have realised only lately that such a software tool could fit the way of one's expression. But then they are suddenly not going to turn into die-hard C++ or SuperCollider. Perhaps they will choose something, which seems more user-friendly – a visual programming software with DSP integration. Like MaxMSP.
      Imagine the following example (of mine). After some time, I wanted to rewrite my older patch into code for the reasons of clarity. My laptop provides a virtual patchbay for various connected synths and MIDI controllers. How could I create that patchbay in Max? 1) using native Max objects: tons of cables or hard to track send/receives (it is 2021, so [dict] objects provide a lot of help though); 2) using [gen], which is still pretty underdeveloped environment IMHO, especially when solving non-DSP related tasks (which is no wonder of course). In this scenario, to communicate with [gen], one needs to create some kind of buffer-based data storage and the result is extremely unintuitive because of the amount of data format conversion that needs to happen from the level of user's UI to buffer (storing a "MyKeyboard" device as a number like -0.00482169). It seems that this task could be easily achieved by the means of [dict]: for every incoming MIDI message its destination should be retrieved (e.g. device\param name) and the message should be then send there. A simple code should reduce the processing part to one object/box titled [routing] in the patcher.
      Right now, the only tool promising both the clarity of the code and a deep integration with Max(MSP) objects is the JS. But hence a tight timing is required with this MIDI-related task, it is not possible to do this! And that's a pitty because then all the potential of the [dict] object is almost lost – the potential to be a handy data structure on the Max native object level.
      Many years ago there used to be an option to run a specified JS function in a high-priority queue, but it was forsaken.
      Back to the main question: imagine that the same, what JS offers in the means of tight integration with MaxMSP was provided for Java instead of JS...
      I found this discussion after I was reading the sources of some mxj objects and I experienced very similar impressions to the ones presented by the OP here: that Java is not that harder to understand than JS.
      As Alexandre mentioned, there is much more commotion in the MaxJS circle than in Java. The Max's documentation also hints to JS much more often than to other languages like Lua or C. TBH, I learned JS because it was advertised in [dict] help file. And it is a great tool, nobody questions that. But perhaps not so much for the live audio processing software...
      As Alexandre expressed it, I also wonder what is the story behind the decision to implement a substantial support for the JS among the Max devs and why it is continued (as we witness with the ascension of the Nodes), while they are much more (CPU) efficient languages there? The handiness of JS also seems to wither when a lot of [js] objects or apps using them are running at once, because the CPU expense starts to add-up. Right now, MaxMSP does not have a user-friendly environment for coding on the level of native object queue. We all love patching cables, we all love [gen], but when there is a need for data expression on a Max level, there is still a gap to fill. One might think that the discovery of this gap alone should be a sign to migrate into another software, but this cannot be the case, since Max's possibilities regarding combining DSP processing with intuitive and remarkably handy UI and graphics as nowhere else are grounded in years of experience and development, resulting in a software that is hard to beat (not to mention the working ethos and the helpful community).
      tl;dr: why high-level low-priority JS instead of lower-level high-priority Java in the live audio processing software?
    • Roman Thilenius's icon
      Roman Thilenius's icon
      Roman Thilenius
      Sep 27 2021 | 12:37 am
      take responsibilty. in the end it is the user who decides what he uses, not the tools. if you use javascript in max - instead of max objects - you can not blame cycling74 for the lack of java support in favor of javascript support. use max objects in max! they can do everything you will ever need to do with midi and more. they only thing worth asking for is bugfixes for max objects. everything else is a voluntary exercise and new options always also create new dependencies with the new possibilities. good code requires time and when you want to produce good code, dont choose the tool or language which is best to write, choose the one which runs best. everyone tells me i should use C++ instead of max for what i am doing, i dont listen == i have to face the consequences.
    • Artur Dobija's icon
      Artur Dobija's icon
      Artur Dobija
      Sep 27 2021 | 7:42 am
      Thank you for your answer!
      I know this feeling very well, the pressure and constant disencouragement... but that's simply += to the feeling like working with Max!
      I do not blame cycling74 (or anybody) for not supporting Java, because Max actually supports Java with some means. I use JS very carefully, mostly for the boring data management or a help when designing the patcher UI. This is also exactly why I found this topic – that you cannot do everything in JS.
      I made a statement, that the question from Alexandre has not been answered yet, because the discussion goes off-topic immediately as if the question was formulated in a wrong way (which I do not believe it is).
    • Iain Duncan's icon
      Iain Duncan's icon
      Iain Duncan
      Sep 27 2021 | 3:02 pm
      I hope this does not come across as thread highjacking, but you might be interested in my project, Scheme for Max. I bring this up because I created it precisely to address many of the concerns you raise. It's not much faster (it's still a high level interpreted language) but it does run in the high priority (timing accurate) thread, has manual garbage collector control, and has direct integration with the Max runtime through the C SDK. I wrote it specifically to enable deeper integration with Max in a high level language that can be hot-reloaded and live-coded in real time. And it's open source, so if you want to, you can add new functions at the C level, which will run dead fast. Of course, some people hate lisp, but a survey of serious computer music projects will demonstrate that lisp has a long history in computer music, and for my money expressing musical concepts in lisp (Scheme is a lisp) is more rewarding, efficient, and elegant than in any other platform I've used. (C/C++, Python, Csound, Max, Pd, etc). https://github.com/iainctduncan/scheme-for-max
    • Mark Durham's icon
      Mark Durham's icon
      Mark Durham
      Sep 28 2021 | 5:16 am
      for every incoming MIDI message its destination should be retrieved (e.g. device\param name) and the message should be then send there.
      It seems like this could be achieved in a simpler way in Max, unless you are talking about a very large number of inputs and outputs. I'd be trying to solve it by tagging input data with the input (eg prepend keyboard), then sorting it on the receiving end via matching (eg route keyboard). It should run fast enough...
    • Artur Dobija's icon
      Artur Dobija's icon
      Artur Dobija
      Sep 28 2021 | 8:24 am
      @Iain Duncan: this looks both impressive and fantastic... time to learn S7 then! I'll definitely have a look. I am very desperate to be able to operate on dicts without patching cables at all (leaving them for a more Max-specific tasks).
      @Mark Durham: thank you for advice! This solution would definitely be fast enough and work for a single and very specific patch. As my project is to create a flexible midi patchbay, I wanted to automate the process of tagging data itself. Before I was using [dict]s and Max send/receives, I was wondering if I could do the routing with a short code. But apart of [gen], which does not support databases, unless we treat [buffer] as such, it is very hard to make some [dict] data processing in higher priority, which is required for midi (audio domain would be even better I guess).
      When working with Max objects there, one does not work on "pure" Max objects. Dict is JSON – even the help file says: "accessing complex structures such as arrays of dictionaries is best done using the js object." (Arrays2 tab). sprintf is from C++ (I guess) and uses different syntax of "%" instead of Max's "$"...
      a cry for an easily accessible as JS but higher priority coding environment is kind of justified here. (I don't think that Java supports dicts, haven't find info in documentation).
    • Iain Duncan's icon
      Iain Duncan's icon
      Iain Duncan
      Sep 28 2021 | 2:19 pm
      Hi Artur, it would be great to have you onboard. Working with dicts (in my biased opinion) in S4M is very pleasant. I have made a bunch of dict to hash-tables and vice versa functions, and s4m will happily convert nested dictionaries to and from nested hashtables, writing and reading to name Max dict objects. I have that covered in the documentation, and if you are new to s7, I've also written a beginner's tutorial for s7. I use them, for example, to persist the contents of my various algorithmic sequencers. Everything that should be persisted is stored in a hash-table, and when I want to save, or send contents to other objects, I can push them to Max dicts and use json. Docs: https://iainctduncan.github.io/scheme-for-max-docs/api.html#dictionary-i-o-hash-tables
      Learn Scheme for Max and s7 Scheme: https://iainctduncan.github.io/learn-scheme-for-max/introduction.html
    • Iain Duncan's icon
      Iain Duncan's icon
      Iain Duncan
      Sep 28 2021 | 2:23 pm
      I also use s4m for complex midi parsing and routing. There is of course the issue that the gc has to run sometimes (as it also does for Java and JS), but in s4m 0.3 there are now various gc and heap controls, and I am able to set it so that this creates no additional latency beyond running with an i/o buffer of 128 or 256 samples, which is acceptable for my purposes. If you really need some fast midi parsing/routing, and you know you're going to leave what you build alone most of the time, you could also do this in a C external. It's daunting the first time, but an external that receives a generic midi message and then does the right thing is a doable project.
    • Ernest's icon
      Ernest's icon
      Ernest
      Oct 16 2021 | 10:17 am
      Mayb e things have improved, but before 2003 I kept having to recode java just aobut every other year, so I dropped it. Since then it went from Sun to Oracle and now I lost track of it, so I guess it's having the same problem still, but I dont know.