`if key in dict` vs. `try/except` – which is more readable idiom?

Exceptions are not conditionals. The conditional version is clearer. That’s natural: this is straightforward flow control, which is what conditionals are designed for, not exceptions. The exception version is primarily used as an optimization when doing these lookups in a loop: for some algorithms it allows eliminating tests from inner loops. It doesn’t have that … Read more

Should a developer aim for readability or performance first? [closed]

You missed one. First code for correctness, then for clarity (the two are often connected, of course!). Finally, and only if you have real empirical evidence that you actually need to, you can look at optimizing. Premature optimization really is evil. Optimization almost always costs you time, clarity, maintainability. You’d better be sure you’re buying … Read more

StringBuilder/StringBuffer vs. “+” Operator

Using String concatenation is translated into StringBuilder operations by the compiler. To see how the compiler is doing I’ll take a sample class, compile it and decompile it with jad to see what’s the generated bytecode. Original class: public void method1() { System.out.println(“The answer is: ” + 42); } public void method2(int value) { System.out.println(“The … Read more

Calling getters on an object vs. storing it as a local variable (memory footprint, performance)

I’d nearly always prefer the local variable solution. Memory footprint A single local variable costs 4 or 8 bytes. It’s a reference and there’s no recursion, so let’s ignore it. Performance If this is a simple getter, the JVM can memoize it itself, so there’s no difference. If it’s a expensive call which can’t be … Read more

How to split a long regular expression into multiple lines in JavaScript?

Extending @KooiInc answer, you can avoid manually escaping every special character by using the source property of the RegExp object. Example: var urlRegex= new RegExp(” + /(?:(?:(https?|ftp):)?\/\/)/.source // protocol + /(?:([^:\n\r]+):([^@\n\r]+)@)?/.source // user:pass + /(?:(?:www\.)?([^\/\n\r]+))/.source // domain + /(\/[^?\n\r]+)?/.source // request + /(\?[^#\n\r]*)?/.source // query + /(#?[^\n\r]*)?/.source // anchor ); or if you want to … Read more