- Home /
why is try and catch ultra slow for this code
I am experimenting with try and catch in a browser (firefox) and also in unity editor. In a browser I can run 10000 of the try statements below in 30 seconds. Unity is running 400 of them in 30 seconds which seems extraordinarily slow. Why is unity so slow in this particular case? This is for a standalone build type working in the editor. If the try line is instead eval("x=2") then it runs quickly in under a second. eval by itself runs very fast. It's only the combination that is super slow.
function testTryCatch(){
var errors=new List.<int>();
function testtrycatch(){
for(var i=0;i<400;i++){
try{
eval("x=y");
}
catch(e){
errors.Add(1);
}
}
Debug.Log(errors.Count);
}
testTryCatch();
Is script debugging on when you use the browser?
Perhaps the stack trace isn't being generated in the browser but in unity it is? (This assumes there is an error)
Ew... eval is gross!
Is there a reason you're using it? Hate to be that guy that doesn't help and says you're doing it wrong, but you maay be doing it wrong. Unless you're hacking something or are forced to by some strange plugin.
Evaluating strings to code is a big no-no in my book. It only follows that it's slow, but I agree, it maybe shouldn't be as slow as you say.
Hope this helps!
script debugging is on in the browser. I don't think it's the eval that's slowing it down but I can check that also.
It's not eval causing the problem by itself. 400 evals runs very fast.
Answer by Eric5h5 · Aug 16, 2013 at 12:44 AM
Unity only runs compiled code, so it has to compile the eval() code on the fly, which is fairly slow. On the plus side, once eval() code is compiled, it runs fast, but you have 400 different strings that have to be compiled.
Also, it doesn't help that you're using dynamic typing. It's really better if you forget that Unityscript is officially called "Javascript", and don't treat it like web Javascript at all. Don't use Array, and type all variables. Pretend you're writing ActionScript3 code instead, and you'll do much better.
I changed the code to get rid of dynamic typing. If eval is correct like eval("x=2") it runs really fast like in under a second.. If eval is wrong like eval("x=y") it runs so that 400 of them take 30 seconds or so.
O$$anonymous$$, so it was mostly the dynamic typing that was the problem, rather than the eval() compiling? I wouldn't have expected that.
No. It's still slow but only if eval has a mistake. Otherwise it's fast. Is there any reason for that?
I'm trying to let the user input some unity code then check it for syntax errors as part of a learning unity project. The speed will matter if they have many lines of code. Is there another way to do something like that?