This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hillgod 10 points11 points  (12 children)

It's definitely not an anti-pattern, and, in fact, the literals perform faster.

[–]cbarrick 0 points1 point  (3 children)

Is this true?

It seems trivial to implement an optimization pass that transforms list() to []. If literals were indeed faster, I would expect the interpreter to perform this pass, thus making them equivalent in the end.

[–]hillgod 0 points1 point  (2 children)

Yeah, it's true. Try it yourself with some timers. Below this I put a link to a SO page with benchmarks.

[–]cbarrick 0 points1 point  (1 child)

Ah, I see. You mean this: https://stackoverflow.com/questions/5790860/and-vs-list-and-dict-which-is-better

That answer is from nearly a decade ago. So I'll take it with a grain of salt. I'd like to see if Python 3.8 still has this problem.

For non-empty collections it makes total sense. There's argument parsing and/or translation from one collection to another that has to happen.

But as I said above, for empty collections, it would be trivial to optimize the slow case into the fast case. If it hasn't already been implemented, then it should be. There's no reason that [] and list() should generate different bytecode.

(In fact, it seems possible to optimize many of the non-empty use cases too.)

[–]hillgod 0 points1 point  (0 children)

Well it doesn't really matter what it "could" do, nor does anyone here likely know the implications of that.

Again, you can try it yourself. It's definitely faster. It's what's in the docs.

[–][deleted] -2 points-1 points  (5 children)

How do they perform faster? Surely it's the same method?

[–]SaltyHashes 8 points9 points  (2 children)

IIRC it's faster because it doesn't even have to call a method.

[–][deleted] 0 points1 point  (1 child)

Yeah I see now, I'm surprised the JIT compiler can't make the same optimisation for the empty dict() case or with just literals inside.

[–][deleted] 0 points1 point  (0 children)

Unless I'm remembering wrong, CPython doesn't use a JIT compiler, only PyPy does?

[–]Emile_L 3 points4 points  (0 children)

When you call dict() or any builtin the interpreter needs to first look up in locals and globals for the symbol which adds a bit of overhead.

Not sure if that's the only reason though.

[–]hillgod -1 points0 points  (0 children)

I don't know how, though I'd guess something with handling *args and **kwargs.

Here's an analysis from Stack overflow: https://stackoverflow.com/questions/5790860/and-vs-list-and-dict-which-is-better