Why tikzmark doesn't work with beamer class?

beamer redefines \pgfmark and adds a number for the slide to the internal name to make if overlay aware. If you look at the aux you can see that you get names like line-code-6-start-1 instead of line-code-6-start. This means that all your \iftikzmark fails.

\documentclass{beamer}
%\documentclass{article}\usepackage{beamerarticle}
%
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{tikzmark,fit,calc}
\usetikzmarklibrary{listings}
\lstset{basicstyle=\ttfamily}
\tikzset{
  balloon/.style={
    draw,
    fill=blue!20,
    opacity=0.4,
    inner sep=4pt,
    rounded corners=2pt
  },
}

\makeatletter

%
\newcommand{\balloon}[4]{%
  \pgfmathtruncatemacro\firstline{%
    #3-1%
  }%
  \iftikzmark{line-#2-\firstline-start-\the \beamer@slideinframe}{%
    \iftikzmark{line-#2-#3-first-\the \beamer@slideinframe}{%
      \xdef\blines{($ ({pic cs:line-#2-\firstline-start} -| {pic
          cs:line-#2-#3-first})!.5!({pic cs:line-#2-#3-first}) $)}%
    }{%
      \iftikzmark{line-#2-#3-start-\the \beamer@slideinframe}{%
        \xdef\blines{({pic cs:line-#2-\firstline-start} -| {pic
            cs:line-#2-#3-start})}%
      }{%
        \xdef\blines{(pic cs:line-#2-\firstline-start)}%
      }%
    }%
  }{%
    \xdef\blines{}%
  }%
  \foreach \k in {#3,...,#4} {%
    \iftikzmark{line-#2-\k-first-\the \beamer@slideinframe}{%
      \xdef\blines{\blines (pic cs:line-#2-\k-first) }%
    }{} \iftikzmark{line-#2-\k-end-\the \beamer@slideinframe}{%
      \xdef\blines{\blines (pic cs:line-#2-\k-end) }%
    }{}%
  }%
  \ifx\blines\empty
  \else
  \edef\temp{\noexpand\tikz[remember picture,overlay]
    \noexpand\node[fit={\blines},balloon] (#1) {};}%
  \temp
  \fi
}
%
\begin{document}


\begin{frame}[fragile]
\balloon{comment}{code}{3}{4}

\begin{lstlisting}[name=code]
Foo Bar Baz
Foo Baz Bar
Bar Foo Baz
Bar Baz Foo
Baz Foo Bar
Baz Bar Foo
\end{lstlisting}
\end{frame}
\end{document}

enter image description here

Addition

An alternative to the redefinition of \ballon is a redefinition of \iftikzmark:

\makeatletter
\renewcommand\iftikzmark[3]{%
    \@ifundefined{save@pt@#1-\the\beamer@slideinframe}{%
      #3%
    }{%
      #2%
    }%
  }%